Joel VanderWerf
3/6/2008 10:02:00 PM
Rodrigo Bermejo wrote:
> "abc".gsub(/./) { |x| x * 2 }
That's the most elegant way to refer to captures, but if speed matters:
"abc".gsub(/(.)/, "\\1\\1")
The "\\1" is always easy to mess up, which is why I generally prefer the
block form.
It's only about a factor of two faster, according to the following, but
that matters sometimes.
require 'benchmark'
Benchmark.bmbm do |b|
s = "abc" * 1_000_000
re = /(.)/
b.report("s.gsub(re){...}") do
s.gsub(re) { |x| x * 2 }
end
b.report("s.gsub(re,...)") do
s.gsub(re, "\\1\\1")
end
end
__END__
Rehearsal ---------------------------------------------------
s.gsub(re){...} 5.970000 0.000000 5.970000 ( 6.009089)
s.gsub(re,...) 2.900000 0.060000 2.960000 ( 3.148006)
------------------------------------------ total: 8.930000sec
user system total real
s.gsub(re){...} 5.760000 0.010000 5.770000 ( 5.925049)
s.gsub(re,...) 2.800000 0.060000 2.860000 ( 2.914432)
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407