May be I am splitting hair, but I was wondering in the following case:
String newString = a + b + c; //case 1 String newString = a.concat(b).concat(c); //case 2 StringBuilder newString = new StringBuilder(); //case 3 newString.append(a); newString.append(b); newString.append(c);
Which is the best to use?
Best I mean in any way.
Reading about these, other posts say that the case 3 is not that optimal performance wise, others that case 1 will end up in case 3 etc.
To be more specific.
E.g., setting all aside, which style is more suitable to see it from another programmer if you had to maintain his code?
Or which would you consider as more programming efficient?
Or you would think is faster etc.
I don't know how else to express this.
An answer like e.g. case 3 can be faster but the vast majority of programmers prefer case 1 because it is most readable is also accepted if it is somehow well elaborated
"Concatenate" joins two specific items together, whereas "append" adds what you specify to whatever may already be there.
+ operator could take any type of input and convert it to a string before append to the target string. The concat method would create new string object as output after appending only if output string has length greater than zero otherwise return the same target string as an output object.
concat() method takes only one argument of string and concatenates it with other string. + operator takes any number of arguments and concatenates all the strings.
Case 1 is concise, expresses the intent clearly, and is equivalent to case 3.
Case 2 is less efficient, and also less readable.
Case 3 is nearly as efficient as case 1, but longer, and less readable.
Using case 3 is only better to use when you have to concatenate in a loop. Otherwise, the compiler compiles case 1 to case 3 (except it constructs the StringBuilder with new StringBuilder(a)
), which makes it even more efficient than your case 3).
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