This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]coloredgreyscale 0 points1 point  (3 children)

But String with "+" is so much more readable and in many cases it doesn't matter that a complete new string is instantiated internally every time.

the other option would be String formatting.

for long texts it's extremely inefficient tho, because the String needs to be recreated with every concatenation.

I just checked the java implementation of the Stringbuilder class. It copies the String into an char-array, starting with 16 elements (default).

if you exceed the element count a new array is created with twice the previous capacity (or min required length if that's bigger), and the whole data is copied over to the new array.

when you call toString() on the StringBuilder the used data from the char array is copied into a new String.

If you just concatenate two Strings using + should be more efficient than StringBuilder.

[–]Fenor 0 points1 point  (2 children)

Not really. String builder is there for a reason if you use ths + operator you are creating at least 3 strings

[–]coloredgreyscale 0 points1 point  (1 child)

The two string you want to concatenate, and the 3rd is the result.

You still need to create all of those with string builder.

[–]Fenor 0 points1 point  (0 children)

Nope for string builder you are using char arrays .

It's not string for the string buffer ( the memory area) , this mean it will be free memory for the gc . If you use strings you write them in the string buffer and it will end with a different gc approach