Returning explicitly is slower
My main concern about returning explicitly is readability. It's a very subjective thing, but in general whenever I see an unnecessary return statement my internal WTF counter increments.
Less subjective though, it has been pointed out that returning explicitly is slower.
Benchmarking in Ruby is easy. Here's how:
require 'benchmark'
def explicit
return "TEST"
end
def implicit
"TEST"
end
n = 100_000_000
Benchmark.bmbm do |x|
x.report("Explicit return") { n.times { explicit } }
x.report("Implicit return") { n.times { implicit } }
end
And here are the results of this particular benchmark:
Rehearsal ---------------------------------------------------
Explicit return 50.380000 0.210000 50.590000 ( 51.000510)
Implicit return 36.200000 0.100000 36.300000 ( 36.454038)
----------------------------------------- total: 86.890000sec
user system total real
Explicit return 47.650000 0.070000 47.720000 ( 47.744167)
Implicit return 35.900000 0.070000 35.970000 ( 35.985493)
This shows that while returning explicitly is slower, like the to_proc hack it's not slow enough to matter. You need to return a huge number of times to see any significant difference.
Does this change my mind? No. Returning explicitly is still ugly.
Update: The above benchmark was run on Ruby 1.8.6. Tom Ward has provided similar benchmarks for Ruby 1.8.7, 1.9 and jRuby 1.1.6 (using n = 10,000,000) which show that the cost of explicitly returning on these platforms in negligible. Still ugly though.
Leave feedback...
Commenting is closed for this article.

This is only the case in 1.8.x. In 1.9 and JRuby there’s no real difference . It’s still just as ugly in any implementation though!