Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False positive SonarQube violation on String concatenation in loop

Tags:

java

sonarqube

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?

like image 243
Sir4ur0n Avatar asked Nov 09 '22 23:11

Sir4ur0n


1 Answers

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.

like image 130
Tunaki Avatar answered Nov 14 '22 23:11

Tunaki