What's the most efficient way to concatenate strings?
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast.
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.
Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.
Rico Mariani, the .NET Performance guru, had an article on this very subject. It's not as simple as one might suspect. The basic advice is this:
If your pattern looks like:
x = f1(...) + f2(...) + f3(...) + f4(...)
that's one concat and it's zippy, StringBuilder probably won't help.
If your pattern looks like:
if (...) x += f1(...)
if (...) x += f2(...)
if (...) x += f3(...)
if (...) x += f4(...)
then you probably want StringBuilder.
Yet another article to support this claim comes from Eric Lippert where he describes the optimizations performed on one line +
concatenations in a detailed manner.
The StringBuilder.Append()
method is much better than using the +
operator. But I've found that, when executing 1000 concatenations or less, String.Join()
is even more efficient than StringBuilder
.
StringBuilder sb = new StringBuilder(); sb.Append(someString);
The only problem with String.Join
is that you have to concatenate the strings with a common delimiter.
Edit: as @ryanversaw pointed out, you can make the delimiter string.Empty
.
string key = String.Join("_", new String[] { "Customers_Contacts", customerID, database, SessionID });
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