Skip to content

Instantly share code, notes, and snippets.

@ferrous26
Created March 26, 2011 18:08
Show Gist options
  • Select an option

  • Save ferrous26/888491 to your computer and use it in GitHub Desktop.

Select an option

Save ferrous26/888491 to your computer and use it in GitHub Desktop.
implicit blocks with yield are 5x faster than explicit blocks
require 'benchmark'
n = 100_000
Benchmark.bmbm do |test|
test.report 'implicit block with yield' do
def test
yield if block_given?
end
n.times do test {} end
end
test.report 'explicit block with yield' do
def test &block
yield if block
end
n.times do test {} end
end
test.report 'implicit block with Proc.new.call' do
def test
Proc.new.call if block_given?
end
n.times do test {} end
end
end
## Ruby 1.8
# Rehearsal ---------------------------------------------------------------------
# implicit block with yield 0.050000 0.000000 0.050000 ( 0.071948)
# explicit block with yield 0.250000 0.020000 0.270000 ( 0.314715)
# implicit block with Proc.new.call 0.310000 0.020000 0.330000 ( 0.381164)
# ------------------------------------------------------------ total: 0.650000sec
# user system total real
# implicit block with yield 0.050000 0.000000 0.050000 ( 0.070865)
# explicit block with yield 0.250000 0.020000 0.270000 ( 0.325773)
# implicit block with Proc.new.call 0.310000 0.020000 0.330000 ( 0.516835)
## Ruby 1.9
# Rehearsal ---------------------------------------------------------------------
# implicit block with yield 0.030000 0.000000 0.030000 ( 0.036943)
# explicit block with yield 0.100000 0.020000 0.120000 ( 0.137407)
# implicit block with Proc.new.call 0.130000 0.010000 0.140000 ( 0.149215)
# ------------------------------------------------------------ total: 0.290000sec
# user system total real
# implicit block with yield 0.020000 0.000000 0.020000 ( 0.028637)
# explicit block with yield 0.110000 0.010000 0.120000 ( 0.137352)
# implicit block with Proc.new.call 0.130000 0.010000 0.140000 ( 0.163363)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment