Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created August 7, 2015 01:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/95ef47502f1976eb4a3c to your computer and use it in GitHub Desktop.
Save JoshCheek/95ef47502f1976eb4a3c to your computer and use it in GitHub Desktop.
# http://blog.honeybadger.io/benchmarking-exceptions-in-ruby-yep-theyre-slow
# $ ruby -v
# ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin13]
#
# $ ruby benchmark.rb
# Calculating -------------------------------------
# method exception 41.808k i/100ms
# begin exception 40.051k i/100ms
# break 99.442k i/100ms
# return 100.254k i/100ms
# throw 76.345k i/100ms
# -------------------------------------------------
# method exception 573.549k (± 9.7%) i/s - 2.843M
# begin exception 574.784k (± 8.3%) i/s - 2.884M
# break 2.881M (± 9.7%) i/s - 14.320M
# return 2.773M (±10.6%) i/s - 13.735M
# throw 1.591M (±10.2%) i/s - 7.864M
# $ ruby -v
# jruby 9.0.0.0 (2.2.2) 2015-07-21 e10ec96 Java HotSpot(TM) 64-Bit Server VM 24.51-b03 on 1.7.0_51-b13 +jit [darwin-x86_64]
#
# $ ruby benchmark.rb
# Calculating -------------------------------------
# method exception 525.000 i/100ms
# begin exception 1.042k i/100ms
# break 59.452k i/100ms
# return 60.555k i/100ms
# throw 40.076k i/100ms
# -------------------------------------------------
# method exception 11.861k (± 9.1%) i/s - 58.800k
# begin exception 11.766k (± 8.5%) i/s - 58.352k
# break 1.082M (± 6.8%) i/s - 5.410M
# return 1.102M (± 6.7%) i/s - 5.511M
# throw 588.593k (± 8.2%) i/s - 2.926M
# $ ruby -v
# rubinius 2.5.7 (2.1.0 d4fdeaad 2015-06-16 3.5.1 JI) [x86_64-darwin14.4.0]
#
# $ ruby benchmark.rb
# Calculating -------------------------------------
# method exception 23.407k i/100ms
# begin exception 51.847k i/100ms
# break 182.347k i/100ms
# return 196.666k i/100ms
# throw 48.064k i/100ms
# -------------------------------------------------
# method exception 682.386k (± 7.8%) i/s - 3.394M
# begin exception 652.175k (± 5.5%) i/s - 3.266M
# break 2.689M (± 5.5%) i/s - 13.494M
# return 2.535M (± 8.3%) i/s - 12.587M
# throw 625.740k (± 4.6%) i/s - 3.124M
require 'benchmark/ips'
def exit_via_exception_rescued_at_method
5.times do
raise RuntimeError
end
rescue
end
def exit_via_exception_rescued_in_begin
begin
5.times do
raise RuntimeError
end
rescue
end
end
def exit_via_break
5.times do
break
end
end
def exit_via_return
5.times do
return
end
end
def exit_via_throw
catch :done do
5.times do
throw :done
end
end
end
Benchmark.ips do |x|
x.report("method exception") { exit_via_exception_rescued_at_method }
x.report("begin exception") { exit_via_exception_rescued_in_begin }
x.report("break") { exit_via_break }
x.report("return") { exit_via_return }
x.report("throw") { exit_via_throw }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment