Why does IntelliJ wants me to change this?

Viewed 281

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.

2 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.

I am assuming you are referring to this:

enter image description here

This is not actually a fix "problem" with your code, as indicated by the pencil icon. Fixes to problems with your code are identified with a lightbulb, such as not using the value of thing:

enter image description here

The pencil just means "here's a shortcut to change your code, so you don't have to change it manually". Changing a a += b to a = a + b usually isn't that much work, but other things, like changing a for-each loop to a regular for loop, is.

enter image description here

This could be useful if you suddenly remembered that you need the index of the array for something.

Related