Aller au contenu

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.

def matches(lines, word)
lines.select do |line|
line =~ Regexp.new("\\b#{word}\\b")
end
end
def matches(lines, word)
pattern = Regexp.new("\\b#{word}\\b")
lines.select { |line| line =~ pattern }
end

Compile the regular expression once outside the loop or hot path and reuse it.