Implicit blocks with yield are faster than explicit blocks with #call
.
require 'benchmark/ips'
def explicit(&block)
block.call
end
def implicit
yield
end
Benchmark.ips do |bm|
bm.report("explicit block") do
explicit { "Hello, world" }
end
bm.report("implicit block") do
implicit { "Hello, world" }
end
end
Higher numbers are better. Iterations per second.
Calculating -------------------------------------
explicit block 27483 i/100ms
implicit block 60237 i/100ms
-------------------------------------------------
explicit block 522159.9 (±10.2%) i/s - 2583402 in 5.033353s
implicit block 2420161.8 (±9.6%) i/s - 11926926 in 5.015945s
Not sure this is always the way to go as an explicit block reveals intent and is clearer IMO, but very useful to know.