Skip to content

Instantly share code, notes, and snippets.

@mdamaceno
Last active June 21, 2024 19:53
Show Gist options
  • Save mdamaceno/0a3d3e9cbc8448d67e3f0f2c20f72226 to your computer and use it in GitHub Desktop.
Save mdamaceno/0a3d3e9cbc8448d67e3f0f2c20f72226 to your computer and use it in GitHub Desktop.
Benchmark regular loop vs loop with rescue in Ruby
ruby 2.6.6p146 (2020-03-31 revision 67876) [-darwin23]
Warming up --------------------------------------
regular loop 2.135k i/100ms
loop with rescue 193.201k i/100ms
Calculating -------------------------------------
regular loop 21.215k (± 2.1%) i/s - 106.750k in 5.034189s
loop with rescue 1.910M (± 3.0%) i/s - 9.660M in 5.062752s
require 'benchmark/ips'
class LoopWithRescue
def initialize(attempts: 1)
raise 'attempts must be greater than 0' if attempts.zero? || attempts.negative?
@attempts = attempts
end
def run
@counter ||= 0
yield
raise
rescue
@counter += 1
retry if @counter < @attempts
end
end
class RegularLoop
def initialize(attempts: 1)
raise 'attempts must be greater than 0' if attempts.zero? || attempts.negative?
@attempts = attempts
end
def run
(1..@attempts).each do
yield
end
end
end
Benchmark.ips do |b|
n = 1_000
value1 = RegularLoop.new(attempts: n)
value2 = LoopWithRescue.new(attempts: n)
b.report('regular loop') do
value1.run do
result = 'echoing'
end
end
b.report('loop with rescue') do
value2.run do
result = 'echoing'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment