Prefer match? over =~ to avoid MatchData#8138
Merged
tagliala merged 1 commit intoNov 17, 2023
Merged
Conversation
When the specific `MatchData` object is not needed, using
`regexp.match?` is preferred over `=~` as it avoids the creation of a
MatchData object, resulting in improved performance and reduced memory
usage.
Example:
```rb
PARTS = ["admin", "users", "2b2f0fc2-9a0d-41b8-b39d-aa21963aaee4"]
%i[ips memory].each do |benchmark|
Benchmark.send(benchmark) do |x|
x.report('=~') { PARTS.each { |part| part =~ ID_FORMAT_REGEXP } }
x.report('match?') { PARTS.each { |part| ID_FORMAT_REGEXP.match?(part) } }
x.compare!
end
end
```
```
Comparison (IPS):
match?: 943080.8 i/s
=~: 621955.5 i/s - 1.52x (± 0.00) slower
Comparison (Memory):
match?: 0 allocated
=~: 168 allocated - Infx more
```
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## master #8138 +/- ##
=======================================
Coverage 99.05% 99.05%
=======================================
Files 184 184
Lines 4745 4746 +1
=======================================
+ Hits 4700 4701 +1
Misses 45 45 ☔ View full report in Codecov by Sentry. |
javierjulio
approved these changes
Nov 17, 2023
javierjulio
left a comment
Member
There was a problem hiding this comment.
Thanks! Odd that the Performance/RegexpMatch rule didn't pick this up.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When the specific
MatchDataobject is not needed, usingregexp.match?is preferred over=~as it avoids the creation of a MatchData object, resulting in improved performance and reduced memory usage.Example: