Skip to content

Instantly share code, notes, and snippets.

@jordelver
Last active April 8, 2018 02:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jordelver/0cc4daf20843cfa3902c to your computer and use it in GitHub Desktop.
Save jordelver/0cc4daf20843cfa3902c to your computer and use it in GitHub Desktop.

Idea from @sferik's talk at Baruco 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment