From: Joel VanderWerf Date: 2008-03-08T13:45:24+09:00 Subject: Re: duplicating characters in a string 7stud -- wrote: > And taking your non-perl champion: > > s.gsub(/(.)/, '\1\1') > > (I refuse to consider any code that uses perl syntax), and pitting it > against: > > s = 'abc' > new_str = "" > s.each_byte do |byte| > 2.times do > new_str << byte > end > end > > > I get: > > gsub: > t1 exec time(1,000,000 loops): 5.625847 total > > each_byte: > t2 exec time(1,000,000 loops): 5.325978 total Hm, I don't see an improvement, unless I replace 2.times... with an explicit unrolling of that inner loop (which is heading downhill in the elegance department): require 'benchmark' Benchmark.bmbm do |b| s = "abc" * 1_000_000 re = /(.)/ b.report("s.gsub(re) {|x| x*2}") do s.gsub(re) {|x| x*2} end b.report("s.gsub(re, '\1\1')") do s.gsub(re, '\1\1') end b.report("7stud1") do new_str = "" s.each_byte do |byte| 2.times do new_str << byte end end end b.report("7stud2") do new_str = "" s.each_byte do |byte| new_str << byte << byte end end end __END__ Rehearsal --------------------------------------------------- s.gsub(re){...} 6.220000 0.010000 6.230000 ( 6.325230) s.gsub(re,...) 3.020000 0.060000 3.080000 ( 3.115286) 7stud 4.110000 0.000000 4.110000 ( 4.142912) 7stud 2.050000 0.000000 2.050000 ( 2.072398) ----------------------------------------- total: 15.470000sec user system total real s.gsub(re){...} 5.910000 0.020000 5.930000 ( 5.993456) s.gsub(re,...) 3.000000 0.000000 3.000000 ( 3.017119) 7stud 4.100000 0.020000 4.120000 ( 4.300772) 7stud 2.030000 0.010000 2.040000 ( 2.068190) -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407