Skip to content

Instantly share code, notes, and snippets.

@tadman
Created January 27, 2015 19:42
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 tadman/ca6aa45faf7c16c04075 to your computer and use it in GitHub Desktop.
Save tadman/ca6aa45faf7c16c04075 to your computer and use it in GitHub Desktop.
Comparison of various block delegation methods in Ruby
#!/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