Last active
December 10, 2015 19:36
-
-
Save backpackerhh/cf5e171775b8585c9fc7 to your computer and use it in GitHub Desktop.
Performance of different block invocations using Ruby 2.1.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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