Skip to content

Instantly share code, notes, and snippets.

@bf4
Created June 14, 2016 03:42
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 bf4/5a576b9a46b4c63a8fe942dbc47aaba8 to your computer and use it in GitHub Desktop.
Save bf4/5a576b9a46b4c63a8fe942dbc47aaba8 to your computer and use it in GitHub Desktop.
Ruby raise/rescue vs. throw/catch. tl;dr throw/catch is much faster
require 'benchmark/ips'
Benchmark.ips do |x|
x.report(:raise_rescue) do
begin
raise ArgumentError
rescue ArgumentError
end
end
x.report(:throw_catch) do
begin
catch(:halt) do
throw(:halt)
end
end
end
x.compare!
end
# Ruby 2.2.4 on OSX
# Warming up --------------------------------------
# raise_rescue 58.744k i/100ms
# throw_catch 157.030k i/100ms
# Calculating -------------------------------------
# raise_rescue 704.836k (± 6.7%) i/s - 3.525M in 5.023761s
# throw_catch 2.532M (± 5.3%) i/s - 12.719M in 5.037449s
#
# Comparison:
# throw_catch: 2532310.2 i/s
# raise_rescue: 704835.7 i/s - 3.59x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment