Skip to content

Instantly share code, notes, and snippets.

@carlosparamio
Last active December 24, 2015 06:59
Show Gist options
  • Save carlosparamio/6760567 to your computer and use it in GitHub Desktop.
Save carlosparamio/6760567 to your computer and use it in GitHub Desktop.
Block declaration benchmark
require "benchmark"
def speak_with_block_and_yield(&block)
yield if block_given?
end
def speak_with_block_and_call(&block)
block.call if block_given?
end
def speak_with_proc_and_call(block)
block.call
end
def speak_without_block_and_yield
yield if block_given?
end
n = 1_000_000
Benchmark.bmbm do |x|
x.report("&block + yield") do
n.times { speak_with_block_and_yield { "ook" } }
end
x.report("&block + call") do
n.times { speak_with_block_and_call { "ook" } }
end
x.report("proc + call") do
proc = Proc.new { "ook" }
n.times { speak_with_proc_and_call(proc) }
end
x.report("yield") do
n.times { speak_without_block_and_yield { "ook" } }
end
end
Rehearsal --------------------------------------------------
&block + yield 0.960000 0.050000 1.010000 ( 1.017942)
&block + call 1.080000 0.050000 1.130000 ( 1.122803)
proc + call 0.270000 0.330000 0.600000 ( 0.606673)
yield 0.250000 0.000000 0.250000 ( 0.244251)
----------------------------------------- total: 2.990000sec
user system total real
&block + yield 1.000000 0.050000 1.050000 ( 1.040755)
&block + call 1.090000 0.040000 1.130000 ( 1.133808)
proc + call 0.260000 0.000000 0.260000 ( 0.260821)
yield 0.230000 0.000000 0.230000 ( 0.228444)
Rehearsal --------------------------------------------------
&block + yield 1.590000 0.050000 1.640000 ( 0.877000)
&block + call 1.280000 0.010000 1.290000 ( 0.742000)
proc + call 0.640000 0.000000 0.640000 ( 0.364000)
yield 0.710000 0.010000 0.720000 ( 0.374000)
----------------------------------------- total: 4.290000sec
user system total real
&block + yield 0.210000 0.000000 0.210000 ( 0.204000)
&block + call 0.310000 0.000000 0.310000 ( 0.311000)
proc + call 0.200000 0.000000 0.200000 ( 0.197000)
yield 0.160000 0.000000 0.160000 ( 0.154000)
Rehearsal --------------------------------------------------
&block + yield 1.030000 0.040000 1.070000 ( 1.083940)
&block + call 1.150000 0.030000 1.180000 ( 1.178381)
proc + call 0.290000 0.010000 0.300000 ( 0.287907)
yield 0.250000 0.000000 0.250000 ( 0.254696)
----------------------------------------- total: 2.800000sec
user system total real
&block + yield 0.980000 0.010000 0.990000 ( 0.988161)
&block + call 1.120000 0.000000 1.120000 ( 1.129818)
proc + call 0.280000 0.000000 0.280000 ( 0.279563)
yield 0.240000 0.000000 0.240000 ( 0.248076)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment