Oops I forgot to ask
which one is faster
if x == 5
return true
else
return false
end
or the conditional operator ? :
x == 5 ? true : false
They're about the same speed. Where you _will_ see a small performance
gain, however, is leaving off the call to the return method
altogether. The value of the last expression in a method is the return
value. The only time to use return if you need to exit a method early.
(And this practice is considered a bad idea by some people in many
situations.)
require 'benchmark'
def ternary_return1( x )
return ( x==5 ? true : false )
end
def ternary_return2( x )
x==5 ? (return true) : (return false)
end
def if_return1( x )
return (if x == 5
true
else
false
end)
end
def if_return2( x )
if x == 5
return true
else
return false
end
end
def ternary_expression( x )
x == 5 ? true : false
end
def if_expression( x )
if x == 5
true
else
false
end
end
values = (1..8).to_a * 500_000
method_names = %w| ternary_return1 ternary_return2
if_return1 if_return2
ternary_expression if_expression |
Benchmark.bmbm{ |x|
method_names.each{ |name|
meth = method( name )
x.report( name ){
values.each{ |n|
meth.call( n )
}
}
}
}
Rehearsal ------------------------------------------------------
ternary_return1 6.125000 0.000000 6.125000 ( 6.157000)
ternary_return2 5.859000 0.000000 5.859000 ( 5.906000)
if_return1 6.016000 0.000000 6.016000 ( 6.047000)
if_return2 5.906000 0.000000 5.906000 ( 5.953000)
ternary_expression 5.453000 0.000000 5.453000 ( 5.484000)
if_expression 5.672000 0.000000 5.672000 ( 5.687000)
-------------------------------------------- total: 35.031000sec
user system total real
ternary_return1 6.047000 0.000000 6.047000 ( 6.078000)
ternary_return2 6.250000 0.000000 6.250000 ( 6.282000)
if_return1 6.032000 0.000000 6.032000 ( 6.063000)
if_return2 6.157000 0.000000 6.157000 ( 6.187000)
ternary_expression 5.656000 0.000000 5.656000 ( 5.703000)
if_expression 5.750000 0.000000 5.750000 ( 5.781000)