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) -- thanks, -pate ------------------------- Duty makes us do things, Love make us do things well. http://on-ruby.blogspot.com http://eldersjournal.blogspot.com