Skip to content

Instantly share code, notes, and snippets.

@JunichiIto
Created December 14, 2017 04:39
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 JunichiIto/bd63f6393e98e210127f42cd37a5b5eb to your computer and use it in GitHub Desktop.
Save JunichiIto/bd63f6393e98e210127f42cd37a5b5eb to your computer and use it in GitHub Desktop.
How slow Ruby exception is?
# Based on http://blog.honeybadger.io/benchmarking-exceptions-in-ruby-yep-theyre-slow/
require 'benchmark/ips'
def find_by
nil
end
def find_by!
raise 'Not found'
end
def via_exception
find_by!
rescue
'No message'
end
def via_if
if user = find_by
user.message
else
'No message'
end
end
def via_safe_nav_op
find_by&.message || 'No message'
end
Benchmark.ips do |x|
x.report("exception") { via_exception }
x.report("if") { via_if }
x.report("safe nav op") { via_safe_nav_op }
end
@JunichiIto
Copy link
Author

JunichiIto commented Dec 14, 2017

The result in Ruby 2.4.2:

Warming up --------------------------------------
           exception
    69.093k i/100ms
                  if   273.168k i/100ms
         safe nav op   277.067k i/100ms
Calculating -------------------------------------
           exception    831.842k (± 6.9%) i/s -      4.146M in   5.011627s
                  if      7.330M (± 6.3%) i/s -     36.605M in   5.017913s
         safe nav op      7.545M (± 6.8%) i/s -     37.681M in   5.020933s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment