Skip to content

Instantly share code, notes, and snippets.

@backpackerhh
Last active December 10, 2015 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save backpackerhh/cf5e171775b8585c9fc7 to your computer and use it in GitHub Desktop.
Save backpackerhh/cf5e171775b8585c9fc7 to your computer and use it in GitHub Desktop.
Performance of different block invocations using Ruby 2.1.2
# Adapted from http://blog.sidu.in/2008/01/ruby-blocks-redux-ruby-190-ruby-186-and.html
require 'benchmark'
def implicit(*args)
yield args.join(' ')
end
def explicit(*args, &block)
block.call args.join(' ')
end
def explicit_binding_before_passing(block, *args)
block.call args.join(' ')
end
n = 1_000_000
Benchmark.bmbm(10) do |r|
r.report('Implicit') do
n.times { implicit('John', 'Doe') { |name| "Hello #{name}" } }
end
r.report('Explicitly binds block when passed') do
n.times { explicit('John', 'Doe') { |name| "Hello #{name}" } }
end
r.report('Explicitly binds block before passing') do
n.times do
the_block = lambda { |name| "Hello #{name}" }
explicit_binding_before_passing(the_block, 'John', 'Doe')
end
end
end
# Rehearsal -------------------------------------------------------------------------
# Implicit 2.470000 0.010000 2.480000 ( 2.482136)
# Explicitly binds block when passed 3.530000 0.000000 3.530000 ( 3.530032)
# Explicitly binds block before passing 3.500000 0.000000 3.500000 ( 3.502021)
# ---------------------------------------------------------------- total: 9.510000sec
# user system total real
# Implicit 2.540000 0.000000 2.540000 ( 2.544439)
# Explicitly binds block when passed 3.640000 0.000000 3.640000 ( 3.647409)
# Explicitly binds block before passing 3.610000 0.000000 3.610000 ( 3.616882)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment