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?
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.
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).
In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
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 .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With