[SonarQube 05] 길이가 늘어나는 문자열은 String 대신 StringBuilder를 쓰자.

소나큐브에서 아래와 같은 minor한 제안을 해주었다.

 

 

Strings are immutable objects, so concatenation doesn’t simply add the new String to the end of the existing string. Instead, in each loop iteration, the first String is converted to an intermediate object type, the second string is appended, and then the intermediate object is converted back to a String. Further, performance of these intermediate operations degrades as the String gets longer. Therefore, the use of StringBuilder is preferred.

Noncompliant Code Example

String str = "";
for (int i = 0; i < arrayOfStrings.length ; ++i) {
  str = str + arrayOfStrings[i];
}

Compliant Solution

StringBuilder bld = new StringBuilder();
  for (int i = 0; i < arrayOfStrings.length; ++i) {
    bld.append(arrayOfStrings[i]);
  }
  String str = bld.toString();

위 코드 참고 전

String kakaoResponse = "";

while ((line = br.readLine()) != null) {
    kakaoResponse += line;
}
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(kakaoResponse);

 

위 코드 참고 후

StringBuilder kakaoResponse = new StringBuilder();

while ((line = br.readLine()) != null) {
    kakaoResponse.append(line);
}
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(kakaoResponse.toString());