Skip to content

Instantly share code, notes, and snippets.

@mchung
Last active August 5, 2018 23:14
Show Gist options
  • Save mchung/2468091e0cac7d83ab6c156a98ae4327 to your computer and use it in GitHub Desktop.
Save mchung/2468091e0cac7d83ab6c156a98ae4327 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
class A
def test
10.times do
yield
end
end
end
class B
def test(&block)
10.times do
block.call
end
end
end
Benchmark.ips do |x|
x.report '10000 yield' do
obj = A.new
10000.times do
obj.test{ 1 + 1 }
end
end
x.report '10000 block.call' do
obj = B.new
10000.times do
obj.test{ 1 + 1 }
end
end
x.compare!
end
Benchmark.ips do |x|
x.report '100000 yield' do
obj = A.new
100000.times do
obj.test{ 1 + 1 }
end
end
x.report '100000 block.call' do
obj = B.new
100000.times do
obj.test{ 1 + 1 }
end
end
x.compare!
end
# › ruby bm.rb
# Warming up --------------------------------------
# 10000 yield 13.000 i/100ms
# 10000 block.call 6.000 i/100ms
# Calculating -------------------------------------
# 10000 yield 137.142 (± 4.4%) i/s - 689.000 in 5.033151s
# 10000 block.call 61.924 (± 4.8%) i/s - 312.000 in 5.049831s
# Comparison:
# 10000 yield: 137.1 i/s
# 10000 block.call: 61.9 i/s - 2.21x slower
# Warming up --------------------------------------
# 100000 yield 1.000 i/100ms
# 100000 block.call 1.000 i/100ms
# Calculating -------------------------------------
# 100000 yield 13.730 (± 7.3%) i/s - 69.000 in 5.033701s
# 100000 block.call 6.233 (± 0.0%) i/s - 32.000 in 5.139911s
# Comparison:
# 100000 yield: 13.7 i/s
# 100000 block.call: 6.2 i/s - 2.20x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment