Memory Leak in StringBuilder when using Insert() and Clear()

后端 未结 2 876
广开言路
广开言路 2020-12-11 07:51

I need to add some lines to a StringBuilder, where the line added last should be at the beginning of the string and the oldest at the end. I add a new line like this:

<
相关标签:
2条回答
  • 2020-12-11 08:26

    We ran into the same issue with

    Replace()
    

    when we updated our web app from .net 2 to .net 4.

    Apparently the implementation of StringBuilder changed. See How the StringBuilder class is implemented? Does it internally create new string objects each time we append?

    The solutions we looked at:

    1. Do not reuse StringBuilder (that's what we decided to do after a big rewrite)
    2. Write our own implementation of SB
    3. Use .NET 2.0
    0 讨论(0)
  • 2020-12-11 08:34

    I would say that the behaviour is to be expected:

    Clear()
    

    The doc states:

    Removes all characters from the current StringBuilder instance.[...] Calling the Clear method does not modify the current instance's Capacity or MaxCapacity property.see Documenation

    So Clear() removes the content but keeps the memory allocated.

    Insert()
    

    Here the doc states that the previous content is shifted and the capacity adjusted as needed. (doc) This is not completely clear, but I assume that new memory capacity + new length is allocated and the rest copied over. Now. this may not be the optimal solution, but I figure that this is the way it is implemented. So the out-of-memory situation is to be expected.


    Another suggestion: Always inserting at the first position is - regardless of the implementation - pretty expensive. If you need the result only once consider using a List<string> where you insert the new lines at position 0 and then iterate over the list once and build the string.


    Edit:

    After looking at the (assumed) source I think that StringBuilder is indeed allocatign a new instance as 'chunk' for every insert - regardless of any other romm available. I followed the calls down to MakeRoom where at line 2044 a new chunk is allocated.

    0 讨论(0)
提交回复
热议问题