Regex recompiled in loop (ARCH4073)
Ce contenu n’est pas encore disponible dans votre langue.
Key java.performance.regex-recompiled-in-loop · Severity warning · Category performance
Pattern.compile and String.matches recompile the regex on every call. Inside a loop this recompiles a constant pattern repeatedly, incurring noticeable cost.
Incorrect
Section titled “Incorrect”for (String line : lines) { if (Pattern.compile("\\d{4}-\\d{2}").matcher(line).find()) { accept(line); }}Correct
Section titled “Correct”Pattern pattern = Pattern.compile("\\d{4}-\\d{2}");for (String line : lines) { if (pattern.matcher(line).find()) { accept(line); }}Compile the Pattern once outside the loop and reuse it across iterations.