Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IntelliJ wants me to change this?

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.

like image 937
Jeex Avatar asked Sep 17 '25 01:09

Jeex


1 Answers

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.

like image 102
Manushin Igor Avatar answered Sep 18 '25 16:09

Manushin Igor