```On 10/7/2010 8:28 AM, Intransition wrote:
>
> On Oct 7, 12:57 am, Ammar Ali <ammarabu... / gmail.com> wrote:
>
>> It would be interesting to have performance comparisons of the various
>> idioms in common use.
>>
>> In these examples, however, it's not surprising that the first loop (without
>> ||=) would be faster. It's not doing anything really. The second involves
>> testing wether the variable is defined or not, every iteration.
>
> Yep. I wrote it b/c I wanted to know *how much* slower using ||= is.

The issue is one of relevance though.  Of course using ||= is slower
than simply taking whatever value is in the variable, but why do you
care in the first place?

If you just wanted to take the value of a variable, you would never use
||= in the first place.  If you have a need to assign a value to the
variable only if it's not already defined though, then you need ||= or
one of its less idiomatic equivalents.

The point of comparison profiling like this is to find ways to improve
compares two fundamentally different operations.  A more relevant
comparison would be as follows:

n = 1000000

puts "#{n} Times"

t = Time.now

@c = :c
n.times do
@c = :c unless @c
@c
end

puts "     Optional set then get (verbose) : #{Time.now - t} seconds"

t = Time.now

@b = :b
n.times do
@b = @b || :b
end

puts "Optional set then get (less verbose) : #{Time.now - t} seconds"

t = Time.now

n.times do
@a ||= :a
end

puts "   Optional set then get (idiomatic) : #{Time.now - t} seconds"

ruby 1.9.2p0 (2010-08-18) [i386-mingw32]
1000000 Times
Optional set then get (verbose) : 0.125004 seconds
Optional set then get (less verbose) : 0.140628 seconds
Optional set then get (idiomatic) : 0.156254 seconds

ruby 1.8.7 (2010-06-23 patchlevel 299) [i386-mingw32]
1000000 Times
Optional set then get (verbose) : 0.20313 seconds
Optional set then get (less verbose) : 0.218756 seconds
Optional set then get (idiomatic) : 0.187505 seconds

In this light, the idiomatic method compares favorably; however, I do
find it odd that Ruby 1.9.2 seems to take a hit on the relative
performance of the idiomatic method as compared to Ruby 1.8.7.

-Jeremy

```