Created
December 14, 2017 04:39
-
-
Save JunichiIto/bd63f6393e98e210127f42cd37a5b5eb to your computer and use it in GitHub Desktop.
How slow Ruby exception is?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result in Ruby 2.4.2: