Performance issues with nested loops and string concatenations

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

    Use a StringBuilder instead of several million concatenations.

    If you concatenate 2 strings, this means the system allocates new memory to contain both of them, and then copies both in. A zillion large memory allocations and copy actions become slow very fast.

    What StringBuilder does is reduce this immensely by allocating 'in advance', thus only having to grow the buffer a few times and just copying it in, eliminating the by far slowest factor of your loop.

提交回复
热议问题