+
within loops is costly and should be replaced by a StringBuffer
/StringBuilder
JAVA-P1006231 for (int i = 0; i < givenCommand.length; i++) {
232 String args = givenCommand[0];
233 for (int j = 1; j <= i; j++) {
234 args += " " + givenCommand[j];235 }
236 if (list.contains(args.toLowerCase())) {
237 contains = true;
The method seems to be building a String
using concatenation in a loop. In each iteration, the String
is converted to a StringBuffer
/StringBuilder
, appended to, and converted back to a String
.
This can lead to a cost of `O(n^2)`` where n is the number of iterations, as the growing string is recopied in each iteration. This issue is detected only on Java versions 8 and below.
String s = "";
for (int i = 0; i < field.length; ++i) {
s = s + field[i];
}
Create a StringBuffer
outside the loop, then update it from within.
StringBuffer buf = new StringBuffer();
for (int i = 0; i < field.length; ++i) {
buf.append(field[i]);
}
String s = buf.toString();