How do I get .NET to garbage collect aggressively?

后端 未结 12 792
情书的邮戳
情书的邮戳 2020-12-02 14:33

I have an application that is used in image processing, and I find myself typically allocating arrays in the 4000x4000 ushort size, as well as the occasional float and the l

12条回答
  •  没有蜡笔的小新
    2020-12-02 14:52

    Just an aside: The .NET garbage collector performs a "quick" GC when a function returns to its caller. This will dispose the local vars declared in the function.

    If you structure your code such that you have one large function that allocates large blocks over and over in a loop, assigning each new block to the same local var, the GC may not kick in to reclaim the unreferenced blocks for some time.

    If on the other hand, you structure your code such that you have an outer function with a loop that calls an inner function, and the memory is allocated and assigned to a local var in that inner function, the GC should kick in immediately when the inner function returns to the caller and reclaim the large memory block that was just allocated, because it's a local var in a function that is returning.

    Avoid the temptation to mess with GC.Collect explicitly.

提交回复
热议问题