Returning Explicitly Is Slower

November 11, 2009 · 1 min read

My main objection to returning explicitly is readability. It is a subjective thing, but every time I see an unnecessary return statement my internal WTF counter ticks up.

Less subjectively, it has been pointed out that returning explicitly is actually slower. Let's measure it.

Benchmarking in Ruby is easy:

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:

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)

So yes, returning explicitly is slower — but like the Symbol#to_proc question, it is not slow enough to matter in practice. You need an enormous number of returns before the difference becomes significant.

Does this change my mind? No. Returning explicitly is still ugly.

Update: The benchmark above 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 explicit returns on these platforms is negligible. Still ugly though.

These posts are LLM-aided. Backbone, original writing, and structure by Craig. Research and editing by Craig + LLM. Proof-reading by Craig.