Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation in Java - when to use +, StringBuilder and concat [duplicate]

Tags:

java

string

When should we use + for concatenation of strings, when is StringBuilder preferred and When is it suitable to use concat.

I've heard StringBuilder is preferable for concatenation within loops. Why is it so?

Thanks.

like image 375
Manish Mulani Avatar asked Oct 19 '11 07:10

Manish Mulani


People also ask

Why would you want to use StringBuilder instead of string?

If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.

Is StringBuilder more efficient than string concatenation Java?

It is always better to use StringBuilder. append to concatenate two string values. Let us cement this statement using the below micro benchmark.

Which is the efficient way of concatenating the string in Java?

Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.

What is the most efficient way to concatenate many strings together?

When concatenating three dynamic string values or less, use traditional string concatenation. When concatenating more than three dynamic string values, use StringBuilder . When building a big string from several string literals, use either the @ string literal or the inline + operator.


1 Answers

Modern Java compiler convert your + operations by StringBuilder's append. I mean to say if you do str = str1 + str2 + str3 then the compiler will generate the following code:

StringBuilder sb = new StringBuilder(); str = sb.append(str1).append(str2).append(str3).toString(); 

You can decompile code using DJ or Cavaj to confirm this :) So now its more a matter of choice than performance benefit to use + or StringBuilder :)

However given the situation that compiler does not do it for your (if you are using any private Java SDK to do it then it may happen), then surely StringBuilder is the way to go as you end up avoiding lots of unnecessary String objects.

like image 137
Saurabh Avatar answered Sep 21 '22 18:09

Saurabh