Actions
Feature #20182
closedRewrite Array#each in Ruby
Feature #20182:
Rewrite Array#each in Ruby
Status:
Closed
Assignee:
-
Target version:
-
Description
Proposal¶
Rewrite Array#each in Ruby https://github.com/ruby/ruby/pull/6687.
class Array
def each
unless block_given?
return to_enum(:each) { self.length }
end
i = 0
while i < self.length
yield self[i]
i = i.succ
end
self
end
end
Purpose¶
Make it possible for YJIT to optimize ISEQs across Array#each.
Background¶
Whether JIT-compiled or not, calling Ruby from C is more expensive than calling Ruby from Ruby. It also prevents YJIT from making cross-ISEQ optimizations.
This is problematic especially for loop methods written in C like Array#each since the overhead is repeated at every iteration.
Discussions¶
There are a couple of things I'd like to discuss in this ticket:
- @Eregon (Benoit Daloze) has pointed out that there's a race condition in the above implementation.
self[i]would yieldnilif the element was removed by another thread or TracePoint afteri < self.length. Is itArray#each's responsibility to atomically operate on elements, or are users supposed to avoid mutating the array in the middle of its loop? - If
Integer#<,Array#length,Integer#succ, orArray#[]is overridden in an incompatible way, the Ruby implementation may not work correctly. May I assume it's acceptable?
Actions