在C#中从大数据结构中释放内存 [英] Deallocate memory from large data structures in C#

查看:764
本文介绍了在C#中从大数据结构中释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模拟代码中有几个 SortedList<> SortedDictionary<> 结构,我添加随着时间的推移,它们中的数百万项目。问题是垃圾回收器不能快速释放足够的内存,因此对应用程序的性能有很大的打击。我最后一个选择是使用 GC.Collect()方法,以便我可以回收那个内存。有没有人有不同的想法?我知道另一个选择的 Flyweight 模式,但是我希望其他建议不需要我的代码重构。

解决方案

我认为 SortedList 使用数组作为后备字段,这意味着大的 SortedList 在大对象堆上分配。大对象堆可以进行碎片整理,这可能导致内存异常,原则上仍然有足够的内存可用。

请参阅此链接



这可能是您的问题,因为对GC.collect的中间调用会阻止LOH在某些情况下进行严重的碎片整理,这就解释了为什么调用它可以帮助您减少问题。



可以通过将大型对象分割成较小的片段来减轻问题。


I have a fewSortedList<>andSortedDictionary<>structures in my simulation code and I add millions of items in them over time. The problem is that the garbage collector does not deallocate quickly enough memory so there is a huge hit on the application's performance. My last option was to engage theGC.Collect()method so that I can reclaim that memory back. Has anyone got a different idea? I am aware of theFlyweightpattern which is another option but I would appreciate other suggestions that would not require huge refactoring of my code.

解决方案

I think the SortedList uses a array as backing field, which means that large SortedList get allocated on the Large object heap. The large object heap can get defragmentated, which can cause an out of memory exception while in principle there is still enough memory available.
See this link.

This might be your problem, as intermediate calls to GC.collect prevent the LOH from getting badly defragmented in some scenarios, which explains why calling it helps you reduce the problem.

The problem can be mitigated by splitting large objects into smaller fragments.

这篇关于在C#中从大数据结构中释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆