A regular expression with a constant pattern is compiled inside a loop

tx0/kotlin:regex-compiled-in-looprecommendedwarningperformance/regexdepth fastperformance

What it finds

Regex("..."), "...".toRegex() and Pattern.compile("...") parse and compile the pattern each time they run. With a constant pattern inside a loop that work is repeated for nothing; a property or a local outside the loop compiles it once.

From the rule's source, regex_in_loop.rs.

Example from the rule's tests
private val digits = Regex("[0-9]+") fun count(lines: List<String>, pattern: String): Int {    var n = 0    for (line in lines) {        if (Regex("[a-z]+").matches(line)) n++tx0 reports: the pattern is compiled again on every pass of the loop        if (pattern.toRegex().matches(line)) n++        if (digits.matches(line)) n++    }    return lines.count { "x+".toRegex().matches(it) }tx0 reports: the pattern is compiled again}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:regex-compiled-in-loop" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:regex-compiled-in-loop] reason="..."

tx0 explain tx0/kotlin:regex-compiled-in-loop shows the same in the terminal. Found a false positive? Report it.