Regex Recompiled In Loop (ARCH6073)
Ce contenu n’est pas encore disponible dans votre langue.
Key ruby.performance.regex-recompiled-in-loop · Severity warning · Category performance
Building a pattern with Regexp.new inside a loop body recompiles the regex on every iteration. Compile the constant pattern once outside the loop.
Incorrect
Section titled “Incorrect”def matches(lines, word) lines.select do |line| line =~ Regexp.new("\\b#{word}\\b") endendCorrect
Section titled “Correct”def matches(lines, word) pattern = Regexp.new("\\b#{word}\\b") lines.select { |line| line =~ pattern }endCompile the regular expression once outside the loop or hot path and reuse it.