Reputation: 5057
Which one will be better use for Concatenation of String
If i want to build a string from bunch of string variables such as str1 and str2, which one will be better one ???
String str="This the String1 " + str1 + " merged with Sting2 " + str2;
String str=String.format("This the String1 %s merged with Sting2 %s", str1 , str2);
What i think is second one will be better , because first one will suffer from creation of lot of string.
correct me if i am wrong ? and provide feedback on same
Upvotes: 7
Views: 15071
Reputation: 1367
following links may help you.
Is there a difference between String concat and the + operator in Java?
http://www.devdaily.com/blog/post/java/use-string-format-java-string-output
Upvotes: 0
Reputation: 692171
The first one will not suffer from creation of Strings. As everything is static, a single StringBuilder is created, all the parts are appended, and then toString is called. It will be slightly more efficient than the second one, which has to parse the format string. But this is probably not where you will lose or gain much performance.
String concatenation creates lots of temporary objects when you're doing it in a loop:
for (String elem : someList) {
s += elem;
}
This will create a StringBuilder and a String object at each iteration.
Upvotes: 3
Reputation: 300769
It depends on the number of strings you are concatenating. For up to 5 (ish) it probably won't matter.
Measure for your particular circumstances if you really need this optimisation.
Upvotes: 1
Reputation: 1503439
The first won't actually create any extra strings. It will be compiled into something like:
String str = new StringBuilder("This the String1 ")
.append(str1)
.append(" merged with Sting2 ")
.append(str2)
.toString();
Given that the second form requires parsing of the format string, I wouldn't be surprised if the first one actually runs quicker.
However, unless you've got benchmarks to prove that this is really a bit of code which is running too slowly for you, you shouldn't be too worried about the efficiency. You should be more worried about readability. Which code do you find more readable?
Upvotes: 9