Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to concatenate strings?

What's the most efficient way to concatenate strings?

like image 717
jimmij Avatar asked Aug 21 '08 20:08

jimmij


People also ask

What is the correct way to concatenate the 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.

What is the most efficient way to concatenate many strings together Python?

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.

What is the best way to concatenate strings in Java?

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.

Is concatenation faster than join?

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.


2 Answers

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.

like image 180
Lee Avatar answered Sep 24 '22 04:09

Lee


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 }); 
like image 37
TheEmirOfGroofunkistan Avatar answered Sep 24 '22 04:09

TheEmirOfGroofunkistan