Created
June 6, 2024 14:30
-
-
Save ahx/d02199f4996e56b1fdba2cc5a4cd41ee to your computer and use it in GitHub Desktop.
Comparing performance of throw vs raise in Ruby
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
# frozen_string_literal: true | |
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'benchmark-ips' | |
gem 'benchmark-memory' | |
end | |
require 'benchmark/ips' | |
require 'benchmark/memory' | |
Benchmark.ips do |x| | |
x.report('throw') do | |
catch :failure do | |
throw :failure | |
end | |
true | |
end | |
x.report('raise') do | |
raise StandardError | |
rescue StandardError | |
true | |
end | |
x.compare! | |
end | |
Benchmark.memory do |x| | |
x.report('throw') do | |
catch :failure do | |
throw :failure | |
end | |
true | |
end | |
x.report('raise') do | |
raise StandardError | |
rescue StandardError | |
true | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ruby 3.3.1 (2024-04-23 revision c56cd86388) [arm64-darwin23]
Warming up --------------------------------------
throw 460.356k i/100ms
raise 187.610k i/100ms
Calculating -------------------------------------
throw 4.574M (± 7.6%) i/s - 23.018M in 5.065972s
raise 1.772M (±10.2%) i/s - 8.818M in 5.036278s
Comparison:
throw: 4574338.0 i/s
raise: 1771656.7 i/s - 2.58x slower
Calculating -------------------------------------
throw 0.000 memsize ( 0.000 retained)
0.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
raise 680.000 memsize ( 0.000 retained)
2.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
Comparison:
throw: 0 allocated
raise: 680 allocated - Infx more