interesting OutOfMemoryException with StringBuilder

后端 未结 3 1724
时光取名叫无心
时光取名叫无心 2020-11-30 14:02

I have the need to continuously build large strings in a loop and save them to database which currently occasionally yields an OutOfMemoryException.

What

3条回答
  •  忘掉有多难
    2020-11-30 14:44

    With the sizes you mention you are probably running into Large Object Heap (LOH) fragmentation.

    Reusing StringBuilder objects is not a direct solution, you need to get a grip on the underlying buffers.
    If possible, calculate or estimate the size beforehand and pre-allocate.

    And it could help if you round up allocations, let's say to multiples of 20k or so. That could improve reuse.

提交回复
热议问题