From: "k0kubun (Takashi Kokubun) via ruby-core" Date: 2024-01-16T04:18:48+00:00 Subject: [ruby-core:116216] [Ruby master Feature#20182] Rewrite Array#each in Ruby Issue #20182 has been updated by k0kubun (Takashi Kokubun). > As discussed on the PR I think this can be solved by using a Primitive which does both things atomically. We built a nice solution using Primitive https://github.com/ruby/ruby/pull/9533. It wasn't straightforward to write multiple values from a single Primitive without allocating an array, which is why I filed this ticket, but we came up with the idea of passing a pointer to local variables to do so. So discussion (1) is less important now. I'd like to still check on discussion (2) since it would help us "move more of the core library to Ruby" going forward. ---------------------------------------- Feature #20182: Rewrite Array#each in Ruby https://bugs.ruby-lang.org/issues/20182#change-106236 * Author: k0kubun (Takashi Kokubun) * Status: Open * Priority: Normal ---------------------------------------- ## Proposal Rewrite Array#each in Ruby https://github.com/ruby/ruby/pull/6687. ```rb 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: 1. @Eregon has pointed out that there's a race condition in the above implementation. `self[i]` would yield `nil` if the element was removed by another thread or TracePoint after `i < self.length`. Is it `Array#each`'s responsibility to atomically operate on elements, or are users supposed to avoid mutating the array in the middle of its loop? 2. If `Integer#<`, `Integer#length`, `Integer#succ`, or `Array#[]` is overridden in an incompatible way, the Ruby implementation may not work correctly. May I assume it's acceptable? -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/