Search code examples
c#asp.netstring-concatenation

Concatenating List<List<string>> takes a long time


What I had tried till Now

string Value ="";
foreach (List<string> val in L1)
{
   Value = Value + string.Join(",", val) + " // ";
}

Where L1 is of datatype List <List<strings>>

This Works, But its take almost n half hour to complete Is there as many fastest and simple way to achieve this.


Solution

  • I'd suggest use StringBuilder instead of concatenations in a loop like that:

    StringBuilder builder = new StringBuilder();
    foreach (List<string> val in L1)
    {
        builder.Append(string.Join(",", val) + " // ");
    }
    string result = builder.ToString();
    

    When concatenating in a loop it needs to copy the string everytime to a new position in memory with the extra allocated memory. StringBuilder prevents that.

    You can also refer to: