Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e89da97

Browse files
committed
Avoid the block or return pattern to save Proc allocations
Using the block param in a boolean context like this cause it to be allocated. Using it with an `if` or `unless` was optimized in 3.2 (ruby/ruby#6286) but using it with `or` or `and` wasn't. ```ruby def foo(&block) block or return 1 end puts RubyVM::InstructionSequence.of(method(:foo)).disasm == disasm: #<ISeq:foo@(irb):11 (11,0)-(13,3)> (catch: false) local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: 0, kw: -1@-1, kwrest: -1]) [ 1] block@0<Block> 0000 getblockparam block@0, 0 ( 12)[LiCa] 0003 dup 0004 branchif 10 0006 pop 0007 putobject_INT2FIX_1_ 0008 leave [Re] 0009 putnil 0010 leave ``` versus ``` def foo(&block) return 1 if block end puts RubyVM::InstructionSequence.of(method(:foo)).disasm == disasm: #<ISeq:foo@(irb):15 (15,0)-(17,3)> (catch: false) local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: 0, kw: -1@-1, kwrest: -1]) [ 1] block@0<Block> 0000 getblockparamproxy block@0, 0 ( 16)[LiCa] 0003 branchunless 7 0005 putobject_INT2FIX_1_ 0006 leave ( 17)[Re] 0007 putnil ( 16) 0008 leave ```
1 parent 2f13a58 commit e89da97

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

lib/set.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@ def disjoint?(set)
507507
# the element as parameter. Returns an enumerator if no block is
508508
# given.
509509
def each(&block)
510-
block or return enum_for(__method__) { size }
510+
block_given? or return enum_for(__method__) { size }
511511
@hash.each_key(&block)
512512
self
513513
end
@@ -582,7 +582,7 @@ def collect!
582582
# Equivalent to Set#delete_if, but returns nil if no changes were
583583
# made. Returns an enumerator if no block is given.
584584
def reject!(&block)
585-
block or return enum_for(__method__) { size }
585+
block_given? or return enum_for(__method__) { size }
586586
n = size
587587
delete_if(&block)
588588
self if size != n
@@ -591,7 +591,7 @@ def reject!(&block)
591591
# Equivalent to Set#keep_if, but returns nil if no changes were
592592
# made. Returns an enumerator if no block is given.
593593
def select!(&block)
594-
block or return enum_for(__method__) { size }
594+
block_given? or return enum_for(__method__) { size }
595595
n = size
596596
keep_if(&block)
597597
self if size != n

0 commit comments

Comments
 (0)