Last active
December 14, 2015 00:58
-
-
Save dbenhur/5002304 to your computer and use it in GitHub Desktop.
micro-benchmark comparing various ways to capture and forward a block
This file contains 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
#!/usr/bin/env ruby | |
require 'benchmark' | |
require 'forwardable' | |
puts RUBY_DESCRIPTION | |
class TestMe | |
extend Forwardable | |
def_delegators :@arr, :each | |
def initialize arr | |
@arr = arr | |
end | |
def each_block_forward &b | |
@arr.each(&b) | |
end | |
def each_block_call &b | |
@arr.each {|e| b.call(e) } | |
end | |
def each_yield | |
@arr.each { |e| yield e } | |
end | |
end | |
N = 500_000 | |
M = 100 | |
a = (0...M).to_a | |
t = TestMe.new a | |
Benchmark.bmbm do |x| | |
x.report('nop') { N.times { } } | |
x.report('raw') { N.times { a.each {|e| e } } } | |
x.report('block_forward') { N.times { t.each_block_forward {|e| e } } } | |
x.report('block_call') { N.times { t.each_block_call {|e| e } } } | |
x.report('yield') { N.times { t.each_yield {|e| e } } } | |
x.report('delegate') { N.times { t.each {|e| e } } } | |
end | |
__END__ | |
$ ./yield-vs-block.rb | |
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin13] | |
Rehearsal ------------------------------------------------- | |
nop 0.020000 0.000000 0.020000 ( 0.019612) | |
raw 2.490000 0.000000 2.490000 ( 2.500898) | |
block_forward 2.700000 0.010000 2.710000 ( 2.718873) | |
block_call 6.930000 0.010000 6.940000 ( 6.953126) | |
yield 3.700000 0.000000 3.700000 ( 3.709342) | |
delegate 2.690000 0.000000 2.690000 ( 2.696791) | |
--------------------------------------- total: 18.550000sec | |
user system total real | |
nop 0.020000 0.000000 0.020000 ( 0.020016) | |
raw 2.280000 0.000000 2.280000 ( 2.286575) | |
block_forward 2.610000 0.010000 2.620000 ( 2.607132) | |
block_call 6.400000 0.000000 6.400000 ( 6.418502) | |
yield 3.680000 0.010000 3.690000 ( 3.680618) | |
delegate 2.790000 0.000000 2.790000 ( 2.799740) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment