A string is extended with + on every pass of a loop, copying it each time

tx0/java:quadratic-string-buildingrecommendedwarningperformance

What it finds

report += line; in a loop copies the whole string built so far on every pass, since strings cannot change: building a text of n pieces this way takes time proportional to n squared. A StringBuilder appends in place, and String.join or a Collectors.joining does the same for a list.

Reported are += and s = s + ... on a local String variable declared outside the innermost loop around the assignment.

From the rule's source, quadratic_string_building.rs.

Example from the rule's tests
import java.util.List; class Csv {  String join(List<String> cells) {    String line = "";    for (String cell : cells) {      line += cell;tx0 reports: line is copied on every pass of the loop      line = line + ",";tx0 reports: line is copied on every pass of the loop      String local = "";      local += cell;    }    line += "\n";    return line;  }}
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/java:quadratic-string-building" = "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/java:quadratic-string-building] reason="..."

tx0 explain tx0/java:quadratic-string-building shows the same in the terminal. Found a false positive? Report it.