When to use Implicit or Explicit Code Blocks

I am trying to figure out when to encode blocks implicitly or explicitly. Given the following code blocks:

  • Implicit

    def two_times_implicit return "No block" unless block_given? yield yield end puts two_times_implicit { print "Hello "} puts two_times_implicit 
  • Explicit

     def two_times_explicit (&i_am_a_block) return "No block" if i_am_a_block.nil? i_am_a_block.call i_am_a_block.call end puts two_times_explicit { puts "Hello"} puts two_times_explicit 

Is it preferable to use the code one by one? Is there a standard practice and are there cases where someone will work better or differently than another, and where no one will work at all?

+6
source share
2 answers

Getting the block through & creates a new proc object from the block, so it’s better not to use it in terms of efficiency. However, using & usually simplifies the definition of methods that may or may not accept a block, and using & , you can also process blocks with arguments, which is why many prefer.

+5
source

In fact, according to one very interesting reading , the second option is 439% slower ( linked thread on HackerNews).

TL DR: Creating and transferring a block using yield is a very optimized general case in MRI, which is handled by a special C function in the interpreter, and the transfer of &block is done differently and has a lot of overhead for creating a new environment and creating Proc for each call.

To summarize, use &block only if you need to pass it further (for example, to the next function) or somehow change it. Otherwise, use yield as it is faster.

+4
source

All Articles