Performance issues with nested loops and string concatenations

前端 未结 8 652
轻奢々
轻奢々 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:42

    The biggest issue I see with this is the fact you're using textToWrite as a string.

    As strings are immutable so each time the string is changed new memory must be reserved copied from the previous version.

    A far more efficient approach is to use the StringBuilder class which is designed for exactly this type of scenario. For example:

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < m.rows; i++)
    {
        for (int j = 0; j < m.cols; j++)
        {
            sb.Append(m[i, j].ToString());
            if(j < m.cols - 1) // don't add a comma on the last element
            {
              sb.Append(",");
            }
        }
        sb.AppendLine();
    }
    

提交回复
热议问题