public
Last active

Benchmark break vs. catch-throw vs. begin-rescue-end in ruby

  • Download Gist
bench.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
require 'benchmark'
 
Benchmark.bmbm do |x|
 
x.report('Break') do
1_000_000.times do
break
end
end
 
x.report('Catch/Throw') do
1_000_000.times do
catch(:benchmarking) do
throw(:benchmarking)
end
end
end
 
x.report('Raise/Rescue') do
1_000_000.times do
begin
raise StandardError
rescue
# do nothing
end
end
end
 
end
results.txt
1 2 3 4 5 6 7 8 9 10
Rehearsal ------------------------------------------------
Break 0.000000 0.000000 0.000000 ( 0.000017)
Catch/Throw 0.760000 0.300000 1.060000 ( 1.056713)
Raise/Rescue 10.390000 0.590000 10.980000 ( 11.017974)
-------------------------------------- total: 12.040000sec
 
user system total real
Break 0.000000 0.000000 0.000000 ( 0.000005)
Catch/Throw 0.770000 0.290000 1.060000 ( 1.064175)
Raise/Rescue 9.630000 0.580000 10.210000 ( 10.232384)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.