Performance issues with nested loops and string concatenations

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

    Assume the matrix is of size MxM and has N elements. You are building the string in a way that takes O(N^2) (or O(M^4)) in the number of iterations. Each operation must copy what's already there. The issue is not some constant-factor overhead like temporary strings.

    Use StringBuilder.

    String concatenation is more efficient for small number of concatenated strings. For a dynamic number of strings, use StringBuilder.

提交回复
热议问题