Ian Macdonald wrote:
> 
> 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?

For String#replace, this means that you can change a text you have
spread to several places without doing a reassignment again. This can be
handy if you have it a zillion places. (I.e. consider _one_ replace
versus N assignments.)

As for your test, I get the sinking feeling that the assignment part
doesn't really measure anything useful. An assignment is pretty cheap,
the "foo" is probably implemented with some kind of copy-on-write, while
a replace has to write the source string over into the destination
string byte-by-byte. Naturally, the latter would be slower.

One potential efficiency of replace would be to reuse created objects to
avoid creating new objects and using alot of memory. This kind of
optimization is not measured by benchmark.

-- 
(\[ Kent Dahl ]/)_    _~_    _____[ http://www.pvv.org/~kentda/ ]_____/~
 ))\_student_/((  \__d L b__/ (pre-) Master of Science in Technology  )
( \__\_?|?_/__/ ) _)Industrial economics and technological management(
 \____/_?_\____/ (____engineering.discipline_=_Computer::Technology___)