Commit 8a4959f
authored
rubocop: reduce every regex evaluation for performance (#4934)
**Which issue(s) this PR fixes**:
Fixes #
**What this PR does / why we need it**:
This is cosmetic change, it does not change behavior at all. The
following rubocop configuration detects it.
```
Performance/ConstantRegexp:
Enable: true
```
Benchmark result:
```
ruby 3.2.8 (2025-03-26 revision 13f495dc2c) +YJIT [x86_64-linux]
Warming up --------------------------------------
interpret everytime 26.127k i/100ms
interpret once 3.172M i/100ms
Calculating -------------------------------------
interpret everytime 254.171k (± 2.6%) i/s (3.93 μs/i) - 1.280M in 5.040357s
interpret once 33.755M (± 1.7%) i/s (29.62 ns/i) - 171.289M in 5.075867s
Comparison:
interpret once: 33755320.3 i/s
interpret everytime: 254171.5 i/s - 132.81x slower
```
Regex should not be evaluated every time, use /o to evaluate only once
because it expands constant in /#{...}/ expression.
Appendix: benchmark script
```ruby
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'benchmark-ips'
gem 'benchmark-memory'
end
Benchmark.ips do |x|
ZERO_OR_MORE_SPACING = /(?:[ \t\r\n]|\z|\#.*?(?:\z|[\r\n]))*/
x.report("interpret everytime") {
/(?:#{ZERO_OR_MORE_SPACING}\>)/
}
x.report("interpret once") {
/(?:#{ZERO_OR_MORE_SPACING}\>)/o
}
x.compare!
end
```
**Docs Changes**:
N/A
**Release Note**:
N/A
Signed-off-by: Kentaro Hayashi <hayashi@clear-code.com>1 parent 53bcd3c commit 8a4959f
2 files changed
+5
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
98 | 98 | | |
99 | 99 | | |
100 | 100 | | |
101 | | - | |
102 | | - | |
| 101 | + | |
| 102 | + | |
103 | 103 | | |
104 | 104 | | |
105 | | - | |
| 105 | + | |
106 | 106 | | |
107 | 107 | | |
108 | 108 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
83 | 83 | | |
84 | 84 | | |
85 | 85 | | |
86 | | - | |
| 86 | + | |
87 | 87 | | |
88 | 88 | | |
89 | 89 | | |
| |||
98 | 98 | | |
99 | 99 | | |
100 | 100 | | |
101 | | - | |
| 101 | + | |
102 | 102 | | |
103 | 103 | | |
104 | 104 | | |
| |||
0 commit comments