I have some code looking like this (I replaced my business variables with generic ones):
Map<String, String> map = new HashMap<String, String>();
for (int i = 1; i < 10; i++) {
String suffix1 = retrieveValue1(i);
String suffix2 = retrieveValue2(i);
String tag = "prefix";
if (suffix1 != null) {
tag += suffix1;
}
else {
tag += suffix2;
}
map.put(tag.toUpperCase(), "on");
}
What bugs me is that I receive the following SonarQube violation:
Performance - Method concatenates strings using + in a loop
In my opinion this is a false-positive (because there is no real loop on a String here) but I'd like to double check first.
I could not find any similar case with my friend Google.
Is it a false-positive, or is there a real performance loss in my loop please?
Yes, SonarQube is probably getting confused about the use of +=
inside the loop.
String tag = "prefix";
is created inside the loop so there is no String concatenation inside a for
loop and, technically, the warning is a false positive.
Note that you could still use StringBuilder
to append both part of the tag, but you'd have to measure if it's necessary or not.