From: pat eyler Date: 2009-01-10T03:47:42+09:00 Subject: Re: Q: most efficient way to remove duplicate spaces in a string? On Fri, Jan 9, 2009 at 11:29 AM, Chris Shea wrote: > On Jan 9, 11:20 am, Mark Watson wrote: >> I don't usually worry too much about efficiency unless runtime >> performance becomes an issue so I use a_string.split.join(' ') to >> remove extra spaces because the code is short and readable. >> >> This is certainly inefficient. What is the fastest idiom for this >> operation? >> >> Thanks, >> Mark > > Haven't benchmarked it, 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 } end user system total real gsub 6.310000 0.080000 6.390000 ( 7.135028) gsub! 6.300000 0.070000 6.370000 ( 7.064374) split.join 3.940000 0.070000 4.010000 ( 4.160529) or, with bmbm pate@pate:~/scratch$ ./stringcleanup.rb Rehearsal ---------------------------------------------- gsub 6.290000 0.170000 6.460000 ( 7.956565) gsub! 6.370000 0.170000 6.540000 ( 8.128309) split.join 3.990000 0.080000 4.070000 ( 4.832332) ------------------------------------ total: 17.070000sec user system total real gsub 6.220000 0.130000 6.350000 ( 7.613061) gsub! 6.390000 0.080000 6.470000 ( 8.284855) split.join 3.970000 0.120000 4.090000 ( 5.684406) Please, benchmark first. It's not that hard: http://on-ruby.blogspot.com/2008/12/benchmarking-makes-it-better.html > but this sounds like a case for regular > expressions. > > a_string.gsub!(/ +/, ' ') > > HTH, > Chris > > -- thanks, -pate ------------------------- Duty makes us do things, Love make us do things well. http://on-ruby.blogspot.com http://eldersjournal.blogspot.com