Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "+" use in String concatenation affect efficiency? [duplicate]

I have worked with String, StringBuilder and StringBuffer in java.
I thought of this question, while I was thinking from efficiency point of view.

Does "+" use in String concatenation affect efficiency?

like image 548
Saurabh Gokhale Avatar asked Dec 28 '22 16:12

Saurabh Gokhale


1 Answers

Yes, but so little it shouldn't matter most of the time.

Using '+' for string constants is the most efficient as the compiler can perform the concatenation.

If you are joining two Strings, the concat method is the most efficient as it avoids using a StringBuilder.

There is almost never a good reason to use StringBuffer except for backward compatibility. StringBuilder or StringWriter are a better choice. However, it is still used explicitly more often than StringBuilder in the JDK :P

StringBuffer is dead, long live StringBuffer

like image 172
Peter Lawrey Avatar answered Dec 30 '22 10:12

Peter Lawrey