Hi,
I was just wondering what the methods Array#replace, Hash#replace and
String#replace achieve that can’t be done with simple assignment.
I’m going to have a guess and say that assignment of an array, a hash or
a string to an already assigned variable creates a second object and
then changes the variable to point to the new object, whereas the
replace method does not cause a second object to be instantiated, but
simply wipes out the old one.
If my guess is right, then replace is there simply for the sake of
efficiency, in the same way that foo << bar is better than foo += bar.
Well, I’ve just decided to put my theory to the test:
#!/usr/bin/ruby -w
require 'benchmark’
include Benchmark
n = 5000000
bm(12) do |test|
test.report(‘assignment:’) do
foo = "bar"
1.upto(n) do
foo = "foo"
end
end
test.report(‘replacement:’) do
foo = "bar"
1.upto(n) do
foo.replace(“foo”)
end
end
end
user system total real
assignment: 8.210000 0.000000 8.210000 ( 8.202920)
replacement: 12.240000 0.010000 12.250000 ( 12.257115)
So, it would seem that replacement is 50% less efficient than simple
assignment.
What, then, is the purpose of the replace method?
Ian
···
–
Ian Macdonald | Far duller than a serpent’s tooth it is to
System Administrator | spend a quiet youth.
ian@caliban.org |
http://www.caliban.org |
>