Performance issues with nested loops and string concatenations

前端 未结 8 642
轻奢々
轻奢々 2021-01-28 10:43

Can someone please explain why this code is taking so long to run (i.e. >24 hours): The number of rows is 5000, whilst the number of columns is 2000 (i.e. Approximately 10m loop

8条回答
  •  隐瞒了意图╮
    2021-01-28 11:38

    The reason that it takes so long to run is because you are using string concatenation to create a string. For each iteration it will copy the entire string to a new string, so in the end you will have copied strings that adds up to several million times the final string.

    Use a StringBuilder to create the string:

    StringBuilder textToWrite = new StringBuilder();
    for (int i = 0; i < m.rows; i++)
    {
        for (int j = 0; j < m.cols; j++)
        {
            if (j > 0) textToWrite.Append(',');
            textToWrite.Append(m[i, j]);
        }
        textToWrite.AppendLine();
    }
    

提交回复
热议问题