Tim Greer
1/10/2009 8:13:00 PM
pat eyler wrote:
> On Fri, Jan 9, 2009 at 6:20 PM, Clifford Heath <no@spam.please.net>
> wrote:
>> Robert Klemme wrote:
>>>
>>> Note that these behave differently...
>>> Interesting figures btw. I would have guessed that gsub! is fastest
>>> - live and learn
>>
>> It still might be - the benchmark doesn't run long enough to
>> compare the GC overhead of making dozens of little strings
>> that get used once each.
>>
>>
>
> Is this better?
>
> #!/usr/bin/ruby
>
> require 'benchmark'
>
> n = 1_000_000
>
> Benchmark.bm(10) do |x|
> x.report("gsub") { n.times do
> a_string = "This is a test string."
> a_string.gsub(/ +/, ' ')
> end
> }
> x.report("gsub!") { n.times do
> a_string = "This is a test string."
> a_string.gsub!(/ +/, ' ')
> end
> }
> x.report("split.join") { n.times do
> a_string = "This is a test string."
> a_string.split.join(' ')
> end
> }
> x.report("squeeze.strip") { n.times do
> a_string = "This is a test string."
> a_string.squeeze(' ').strip
> end
> }
> end
>
>
>
> $ ./stringcleanup.rb
> user system total real
> gsub 7.170000 0.140000 7.310000 ( 11.034766)
> gsub! 6.900000 0.150000 7.050000 ( 14.113575)
> split.join 4.450000 0.110000 4.560000 ( 7.518476)
> squeeze.strip 3.180000 0.100000 3.280000 ( 4.943830)
>
>
For gsub/gsub!, instead of replacing one or more white space with a
white space, speed it up by replacing two or more white space with a
white space. This saves unneeded processing by not replacing single
white space. I.e., instead of gsub(/ +/, ' '), try gsub(/ +/, ' ') or
gsub(/ {2,}/, ' ') and benchmark them (they should be faster). Of
course, it's still not going to be as fast as split.join or
squeeze.strip (at least depending on the version of ruby used, as older
ruby versions may put squeeze.strip markedly slower than split.join.
--
Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc.
Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers
and Custom Hosting. 24/7 support, 30 day guarantee, secure servers.
Industry's most experienced staff! -- Web Hosting With Muscle!