Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rektide
Created November 10, 2016 19:40
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 rektide/28e1f21765ce19485215b7574ef70730 to your computer and use it in GitHub Desktop.
Save rektide/28e1f21765ce19485215b7574ef70730 to your computer and use it in GitHub Desktop.
ruby rescue cost

What/Why

I as concerned about whether the presence of rescue in Ruby had significant performance impact.

In JavaScript for example try/catch historically has had significant impact itself, even when no exceptions were being thrown.

Based on these benchmarks though, I can see Ruby doesn't seem to have significant cost for defining exception handlers.

Results

Calculating -------------------------------------
           exception    136415 i/100ms
               break    138364 i/100ms
              return    137073 i/100ms
-------------------------------------------------
           exception  4168999.4 (±2.5%) i/s -   20871495 in   5.009678s
               break  4300029.8 (±2.8%) i/s -   21584784 in   5.023858s
              return  4173625.1 (±1.8%) i/s -   20972169 in   5.026599s

Credit

Based off of http://blog.honeybadger.io/benchmarking-exceptions-in-ruby-yep-theyre-slow/ , which measures the cost of using exceptions (not my concern- exceptions are rare, I just wanted to know cost of the handler).

require 'benchmark/ips'
def exit_via_return_with_rescue
5.times do
return
end
rescue
end
def exit_via_break
5.times do
break
end
end
def exit_via_return
5.times do
return
end
end
Benchmark.ips do |x|
x.report("exception") { exit_via_return_with_rescue }
x.report("break") { exit_via_break }
x.report("return") { exit_via_return }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment