Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string concatenation efficiency [duplicate]

Tags:

Is this bad ?

(imagine it's bigger)

int count; //done something to count String myString = "this " + "is " + "my " + "string" + "and " + this.methodCall() + " answer " + "is : " + count; 

or is it better in a StringBuilder/StringBuffer?

like image 742
Mark W Avatar asked Jan 04 '12 11:01

Mark W


People also ask

What is the best way to concatenate strings 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.

Is string concatenation slow Java?

Let me say the reason that string concatenation is slow is because strings are immutable. This means every time you write "+=", a new String is created. This means the way you build up your string is in the worst case, O(n2).

Can I use += for string Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.

Can you use += to concatenate strings?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .


2 Answers

Java compiler will convert it into StringBuilder to increase the performance of repeated string concatenation. http://java.sun.com/docs/books/jls/third%5Fedition/html/expressions.html#15.18.1.2

Its when you are concatenating in a loop compiler can't substitute StringBuilder by itself that's when you should consider from concatenation to StringBuilder.

like image 137
user765635 Avatar answered Oct 10 '22 21:10

user765635


The Javadoc for StringBuffer states from Java 5.0

The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

The compiler will combine the string literals so its the same as writing

String myString = "this is my stringand " + this.methodCall() + " answer is : " + count; 

which is the same as

String myString = new StringBuilder().append("this is my stringand ").append(methodCall()).append(" answer is : ").append(count).toString(); 

I wouldn't worry about the performance unless you need to eliminate garbage from your system, in which case you wouldn't use Strings here. (Its highly unlikely you need to worry about it)

like image 41
Peter Lawrey Avatar answered Oct 10 '22 21:10

Peter Lawrey