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 Concat operator
String str="This the String1 " + str1 + " merged with Sting2 " + str2;
- String format method
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
The first won’t actually create any extra strings. It will be compiled into something like:
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?