Performance issues with nested loops and string concatenations

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

    Because you are creating tons of strings.

    You should use StringBuilder for this.

    StringBuilder sb = new StringBuildeR();
    
    for (int i = 0; i < m.rows; i++)
    {
        bool first = true;
    
        for (int j = 0; j < m.cols; j++)
        {
            sb.Append(m[i, j]);
    
            if (first)
            {
                first = false;
            }
            else
            {
                sb.Append(",");
            }
        }
    
        sb.AppendLine();
    }
    
    string output = sb.ToString();
    

提交回复
热议问题