Issue #17030 has been updated by jeremyevans0 (Jeremy Evans).


Dan0042 (Daniel DeLorme) wrote in #note-21:
> Yeah ok, that sentence wasn't very clear, sorry.
> 
> The first thing is that when compiling a method to an iseq, you have to set a flag on the iseq if the method contains any of the "last_match" pseudo-globals (`$~`, `$&`, `$1`, `Regexp.last_match`, ...)
> 
> Then in `rb_reg_match` (aka `Regexp#=~`), you check if the current iseq has the flag set. This is similar to how `rb_backref_get` gets the last_match object from execution context > control frame > normal control frame > ep > svar > backref. If the flag is not set it means you can use a variant of `reg_match_pos` that only returns the position without using `rb_reg_search` to set the last_match, in the same vein as `rb_reg_match_m_p` (aka `Regexp#match?`).
> 
> But I may be missing a few details here, as I don't have a full understanding of the VM.

Unfortunately, you can't take this approach for VM optimizations without breaking backwards compatibility unless you also have a deoptimization approach that will handle code such as:

```ruby
def a; /(a)/ =~ 'a'; binding; end; a.eval('$1')

def a; /(a)/ =~ 'a'; proc{}; end; a.binding.eval('$1')

def a(c, m); /(a)/ =~ 'a'; c.send(m); end; a(Regexp, :last_match)
```

----------------------------------------
Bug #17030: Enumerable#grep{_v} should be optimized for Regexp
https://bugs.ruby-lang.org/issues/17030#change-87237

* Author: marcandre (Marc-Andre Lafortune)
* Status: Open
* Priority: Normal
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN
----------------------------------------
Currently,

```ruby
array.select { |e| e.match?(REGEXP) }
```

is about three times faster and six times more memory efficient than

```ruby
array.grep(REGEXP)
```

This is because `grep` calls `Regexp#===`, which creates useless `MatchData`.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>