What are the behavioural differences between the following two implementations in Ruby of the thrice
method?
module WithYield
def self.thrice
Here's an update for Ruby 2.x
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
I got sick of writing benchmarks manually so I created a little runner module called benchable
require 'benchable' # https://gist.github.com/naomik/6012505
class YieldCallProc
include Benchable
def initialize
@count = 10000000
end
def bench_yield
@count.times { yield }
end
def bench_call &block
@count.times { block.call }
end
def bench_proc &block
@count.times &block
end
end
YieldCallProc.new.benchmark
Output
user system total real
bench_yield 0.930000 0.000000 0.930000 ( 0.928682)
bench_call 1.650000 0.000000 1.650000 ( 1.652934)
bench_proc 0.570000 0.010000 0.580000 ( 0.578605)
I think the most surprising thing here is that bench_yield
is slower than bench_proc
. I wish I had a little more of an understanding for why this is happening.