Why does IntelliJ wants me to change this?

Jeex :

A simple line of code:

String thing = "Something";
thing += " something else" + " and more.";

IntelliJ IDEA offers to change this line into 4 other ways to accomplish the same result:

String.format()
StringBuilder.append()
java.text.MessageFormat.format()
Replace += with =

Why? What is so wrong with +=? Can anyone explain this please? Thanks.

Manushin Igor :

In general case, the result is not the same. + operator allocates intermediate string, which requires additional memory.

String thing = "Something";
thing += " something else" + " and more."; // two allocations: to compute string inside expression ```" something else" + " and more."```` and to execute ```+=```

By using StringBuilder you don't allocate intermediate result, e.g. less memory is needed.

In your case with short lines and without loops no actual performance boost is expected. However with loops you receive O(N^2) complexity. Please check this answer with explained example.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23153&siteId=1