I have a ruby method that needs to check if a block was passed to it.
A colleague is suggesting that simply checking if block.nil?
is slightly faster in performance and works for named blocks. This is already quite annoying since he is using the named block and invoking it using block.call
rather than yield
which has been shown to be significantly faster, since named blocks are more easy to understand in terms of readability.
Version 1:
def named_block &block
if block.nil?
puts "No block"
else
block.call
end
end
Version 2:
def named_block &block
if !block_given?
puts "No block"
else
block.call
end
end
Benchmarking shows that version 1 is slightly faster than version 2, however a quick look at the source code seems to suggest that block_given?
is thread safe.
What are the main differences between the two approaches? Please help me prove him wrong!
yield
might be perfectly used when named block is given instead of explicitblock.call
. – Binniif !block_given?
negation under two-branchedif
, appeared in the OP, is waaaay worse, thancb.nil?
vsblock_given?
. – Binniblock.call unless block.nil?
vsblock.call if block_given?
, so my post is a variation and I agree it wasn't the best one. That said, I agree with @the_drow, we care about the tradeoffs (and proving I am right) and some of the answers here address those well. – Shoshanashoshanna