fb-contrib
fb-contrib copied to clipboard
Questionable instance of PSC_PRESIZE_COLLECTIONS
PSC_PRESIZE_COLLECTIONS is reported on code of the form:
List<Foo> allFoos = new ArrayList<>();
for (Bar bar : bars) {
allFoos.add(bar.getFoo());
for (Baz baz : bar.getBazs()) {
allFoos.add(baz.getFoo());
}
for (Qux qux : bar.getQuxs()) {
allFoos.add(qux.getFoo());
}
}
for (Quz quz : quzs) {
allFoos.add(quzs.getFoo());
}
While it is true that the required capacity could be precomputed, this would basically double the source code size, be prone to errors, and not be maintenance-friendly. In cases like this, it is not really "known a priori (or at least can be reasonably guessed) how many items are going to be placed in the collection" as claimed by the bug description.
I would suggest to not report this bug pattern if such nested iterations are present, i.e. if the capacity parameter requires more than a simple arithmetic expression (like "foo.size() + bar.size()").