Skip to content

Instantly share code, notes, and snippets.

@matthewrudy
Forked from defunkt/gist:160718
Created August 5, 2009 10:28
Show Gist options
  • Save matthewrudy/162626 to your computer and use it in GitHub Desktop.
Save matthewrudy/162626 to your computer and use it in GitHub Desktop.
# 9 out of 10 microbenchmarks agree: implicit return smokes explicit return
require 'benchmark'
def with_explicit
return 1
end
def with_implicit
1
end
# rails returning
def returning(value)
yield
value
end
def with_returning
returning(1) do
end
end
n = 10_000_000
Benchmark.bmbm do |x|
x.report("explicit") { n.times { with_explicit } }
x.report("implicit") { n.times { with_implicit } }
x.report("returning"){ n.times { with_returning } }
end
# ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
$ ruby test.rb
Rehearsal ---------------------------------------------
explicit 8.190000 4.340000 12.530000 ( 12.705659)
implicit 6.550000 2.430000 8.980000 ( 8.997430)
returning 14.930000 4.820000 19.750000 ( 19.910411)
----------------------------------- total: 41.260000sec
user system total real
explicit 8.410000 4.110000 12.520000 ( 12.826650)
implicit 7.020000 2.320000 9.340000 ( 9.499807)
returning 15.410000 4.550000 19.960000 ( 20.093049)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment