简体   繁体   English

循环中字符串连接的假阳性SonarQube违规

[英]False positive SonarQube violation on String concatenation in loop

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: 让我感到不快的是,我收到了以下SonarQube违规行为:

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. 是的,SonarQube可能对在循环中使用+=感到困惑。

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. 在循环内部创建,因此for循环中没有字符串连接,从技术上讲,警告是误报。

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. 请注意,您仍然可以使用StringBuilder附加标记的两个部分,但是您必须测量是否有必要。

Declare the String variables outside the loop. 在循环外声明String变量。 I think this might solve your problem. 我认为这可以解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM