Skip to content

Instantly share code, notes, and snippets.

@bryanl
Forked from ngauthier/benchmark.rb
Created September 27, 2011 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanl/1245360 to your computer and use it in GitHub Desktop.
Save bryanl/1245360 to your computer and use it in GitHub Desktop.

Using Exceptions to manage control flow in Rails Controllers...

is very very slow

require 'benchmark'
def ifelse
val = rand(1000) >= 30
if val
1
else
2
end
end
def raiserescue3
val = rand(1000) > 30
begin
raise unless val
rescue
2
end
end
def raiserescue1
val = rand(1000) > 10
begin
raise unless val
rescue
2
end
end
def raiserescue01
val = rand(1000) > 1
begin
raise unless val
rescue
2
end
end
Benchmark.bm do |x|
x.report("if/else ") { 10_000_000.times { ifelse } }
x.report("raise/rescue 3%") { 10_000_000.times { raiserescue3 } }
x.report("raise/rescue 1%") { 10_000_000.times { raiserescue1 } }
x.report("raise/rescue 0.1%") { 10_000_000.times { raiserescue01 } }
end
user system total real
if/else 2.720000 0.000000 2.720000 ( 2.718175)
raise/rescue 3% 5.340000 0.210000 5.550000 ( 5.541438)
raise/rescue 1% 3.620000 0.040000 3.660000 ( 3.666966)
raise/rescue 0.1% 2.890000 0.010000 2.900000 ( 2.899297)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment