Created
January 27, 2015 19:42
-
-
Save tadman/ca6aa45faf7c16c04075 to your computer and use it in GitHub Desktop.
Comparison of various block delegation methods in Ruby
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' | |
def with_call(object, &block) | |
block.call(object) | |
end | |
def with_proc(object) | |
Proc.new.call(object) | |
end | |
def with_yield(object) | |
yield(object) | |
end | |
count = 10000000 | |
Benchmark.bm do |x| | |
object = Hash.new { |h,k| h[k] = 0 } | |
x.report("call") { count.times { with_call(object) { |o| o[:call] += 1 } } } | |
x.report("proc") { count.times { with_proc(object) { |o| o[:proc] += 1 } } } | |
x.report("yield") { count.times { with_yield(object) { |o| o[:yield] += 1 } } } | |
end | |
# user system total real | |
# call 9.950000 0.180000 10.130000 ( 10.157157) | |
# proc 10.740000 0.140000 10.880000 ( 10.899302) | |
# yield 2.470000 0.000000 2.470000 ( 2.480088) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment