Craig Demyanovich wrote:

> [Note:  parts of this message were removed to make it a legal post.]
> 
> I was just doing that. :-)
> 
> require 'benchmark'
> 
> n = 1_000_000
> 
> Benchmark.bm(10) do |x|
>  x.report("gsub") { n.times do
>      "This     is  a test   string.".gsub(/ +/, ' ')
>    end
>  }
>  x.report("gsub!") { n.times do
>      "This     is  a test   string.".gsub!(/ +/, ' ')
>    end
>  }
>  x.report("split.join") { n.times do
>      "This     is  a test   string.".split.join(' ')
>    end
>  }
>  x.report("squeeze.strip") { n.times do
>      "This     is  a test   string.".squeeze(' ').strip
>    end
>  }
> end
> 
>                 user     system      total        real
> gsub        4.470000   0.040000   4.510000 (  4.578173)
> gsub!       4.390000   0.020000   4.410000 (  4.468695)
> split.join  3.500000   0.020000   3.520000 (  3.556669)
> squeeze.strip  1.980000   0.010000   1.990000 (  2.003622)
> 
> Regards,
> Craig


The ruby version plays a big role in squeeze.strip, as it's much slower
than split.join with an older version on one of my systems.

Also, try the following variations and see the slight speed increase for
gsub/gsub! (small increase, but interesting to note):

I.e.:

n = 1_000_000

string = "This   is  a test    string."

Benchmark.bm(10) do |x|
 x.report("gsub") { n.times do
        string.gsub(/ +/, ' ')
 end
 }
 x.report("gsub #2") { n.times do
        string.gsub(/ {2,}/, ' ')
 end
 }
 x.report("gsub #3") { n.times do
        string.gsub(/  +/, ' ')
 end
 }

old ruby 1.8.1 on one system:

                user     system      total        real
gsub        9.090000   0.000000   9.090000 (  9.111154)
gsub #2     8.600000   0.000000   8.600000 (  8.643407)
gsub #3     7.560000   0.000000   7.560000 (  7.579185)
gsub!       8.060000   0.000000   8.060000 (  8.061861)
gsub! #2    8.110000   0.000000   8.110000 (  8.115992)
split.join  4.730000   0.000000   4.730000 (  4.733248)
squeeze.strip  6.140000   0.000000   6.140000 (  6.132690)

Ruby 1.8.7 on another system:

                user     system      total        real
gsub        3.660000   0.000000   3.660000 (  3.663209)
gsub #2     3.450000   0.000000   3.450000 (  3.455171)
gsub #3     3.070000   0.000000   3.070000 (  3.065939)
gsub!       3.500000   0.000000   3.500000 (  3.517176)
gsub! #2    3.510000   0.000000   3.510000 (  3.506881)
split.join  2.550000   0.000000   2.550000 (  2.560460)
squeeze.strip  1.580000   0.000000   1.580000 (  1.588717)

I'll see if I can get a chance to upgrade ruby on the older system to
see the results.
-- 
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!