Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficent way of joining strings

I need to concatenate a lot of strings alltogether and put a comma between any of them. I have a list of strings

"123123123213"
"1232113213213"
"123213123"

and I want to get

"123123123213,1232113213213,123213123"

I was wondering what is the best way to achieve that.

I could do this like this:

private List<string> stringList = new List<string> { 
    // a lot of strings in here
    "1234567890", "34343434", "4343434" }; 

string outcome = string.Join(",", stringList.ToArray());

Or maybe:

StringBuilder builder = new StringBuilder();
stringList.ForEach(val => {
    builder.Append(val);
    builder.Append(",");
});

string outcome = builder.ToString();

Which way is better? Do you know better ways to concatenate strings?

like image 456
image Avatar asked May 01 '11 20:05

image


2 Answers

As @Ekkehard said, use the string.Join.

However, you do not need the ToArray() because string.Join has an overload for IEnumerable<string>.

List<string> stringList = new List<string> 
    { "1234567890", "34343434", "4343434" }; 

string outcome = string.Join(",", stringList);

EDIT

As @Kobi said, this will work only C# 4.0. In 3.5 I would do.

var s = new StringBuilder(stringList.Count * 8);
foreach (var item in stringList)
{
   s.Append(item);
   s.Append(',');
}
s.Length -= 1;
string outcome = stringList.ToList();
like image 72
Richard Schneider Avatar answered Nov 09 '22 06:11

Richard Schneider


You should use string.Join() because:

a) it's much more readable, maintainable and easy on the eyes.

b) it uses a StringBuilder internally already, so it's very efficient ( you can confirm yourself using Reflector).

Edit:

string.Join() uses a StringBuilder for the general case of an IEnumerable<T> input. If you already have an array on the other hand it uses some voodoo magic (including FastAllocateString() and UnSafeCharBuffer) to be even faster.

like image 23
BrokenGlass Avatar answered Nov 09 '22 04:11

BrokenGlass