UPDATED as per comment. Here's a way to improve the x method. B is your method, C is the improved version because with this syntax the right side of && never gets executed. Benchmark is the standard Ruby way of doing exactly what the class is intended to be used for easy to read docs. To see why Time.now
is not recommended, see this answer. Also it's common to move the iteration to the Benchmark as to not clutter up your actual methods.
require 'benchmark'
GC.disable
N=50000
class Foo
def a
j = nil
if j
j << 'a'.freeze
else
j = 'not nil'
end
j
end
def b
j = nil
j && j << 'a'.freeze || j = 'not nil'
j
end
def c
j = nil
j && (j << 'a' || j = 'j')
j
end
end
foo = Foo.new
foo.a
foo.b
foo.c
Benchmark.bmbm(10) do |x|
x.report(:a) { N.times {foo.a }}
puts "j is no longer nil, but it's a string #{foo.a} <- see"
x.report(:b) { N.times {foo.b }}
puts "j is equal to #{foo.b} which is a string, not nil"
x.report(:c) { N.times {foo.c }}
puts "look for j, nothing here *#{foo.c}* but emptiness"
end
puts "\n take 2\n"
Benchmark.bmbm(10) do |x|
x.report(:c) { N.times {foo.c }}
x.report(:a) { N.times {foo.a }}
x.report(:b) { N.times {foo.b }}
end
Results:
j is no longer nil, but it's a string not nil <- see
j is equal to not nil which is a string, not nil
look for j, nothing here ** but emptiness
Rehearsal ----------------------------------------------
a 0.005619 0.001018 0.006637 ( 0.007648)
b 0.005097 0.000924 0.006021 ( 0.006847)
c 0.003488 0.000025 0.003513 ( 0.003783)
------------------------------------- total: 0.016171sec
user system total real
a 0.006934 0.000331 0.007265 ( 0.010790)
b 0.004609 0.000086 0.004695 ( 0.005038)
c 0.004939 0.000148 0.005087 ( 0.009489)
take 2
Rehearsal ----------------------------------------------
c 0.004118 0.000097 0.004215 ( 0.005652)
a 0.005844 0.000155 0.005999 ( 0.017280)
b 0.005498 0.000161 0.005659 ( 0.013625)
------------------------------------- total: 0.015873sec
user system total real
c 0.006040 0.000133 0.006173 ( 0.013035)
a 0.005715 0.000081 0.005796 ( 0.006672)
b 0.004042 0.000016 0.004058 ( 0.004220)