A loop over a map's keys looks each value up again with get

tx0/java:key-set-lookupstrictwarningperformance

What it finds

for (String key : counts.keySet()) { use(counts.get(key)); } looks every key up again to get its value. Iterating over counts.entrySet() gives key and value together, without the extra lookups.

From the rule's source, key_set_lookup.rs.

Example from the rule's tests
import java.util.Map; class Totals {  int sum(Map<String, Integer> counts) {    int total = 0;    for (String key : counts.keySet()) {      total += counts.get(key);tx0 reports: each value of counts is looked up again by its key    }    for (Map.Entry<String, Integer> e : counts.entrySet()) {      total += e.getValue();    }    return total;  }}
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 strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:key-set-lookup" = "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:key-set-lookup] reason="..."

tx0 explain tx0/java:key-set-lookup shows the same in the terminal. Found a false positive? Report it.