interesting OutOfMemoryException with StringBuilder

后端 未结 3 1723
时光取名叫无心
时光取名叫无心 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:23

    There is memory but no contiguous segment that can handle the size of your string builder. You have to know that each time the buffer of the string builder is too short, its size is doubled. If you can define (in the ctor) the size of your builder, it's better. You MAY call GC.Collect() when you are done with a large collection of objects.

    Actually, when you have an OutOfMemory, it generaly shows a bad design, you may use the hard drive (temp files) instead of memory, you shouldn't allocate memory again and again (try to reuse objects/buffers/...).

    I STRONGLY advice you to read this post “Out Of Memory” Does Not Refer to Physical Memory from Eric Lippert.

提交回复
热议问题