C# 中的大列表使用了多少空闲内存? [英] How free memory used by a large list in C#?

查看:17
本文介绍了C# 中的大列表使用了多少空闲内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Population 的列表,它包含了很多职位,但在某些时候我会停止使用它.如何释放资源?那么这是部分代码:

I have a list called Population, is a great list of very many positions and at some point I stop using it. How I can free the resources? Then this is part of the code:

 private List <BasePopulation> Population=new List <BasePopulation>();
 Population.SomeMethod();
 Population.Clear();

我使用了 Clear 方法,但不起作用.有什么想法吗?

I used the Clear method, but not works. Any idea?

推荐答案

问题可能是 Clear 没有按照你的想法做.Clear 只是将 List 标记为空,而无需调整它在后台使用的内部数组的大小.但是,它将删除对单个 BasePopulation 实例的所有引用.因此,如果没有其他数据结构引用它们,它们将有资格进行垃圾收集.但是,它不会直接减小 List 的大小.我刚刚使用 ILSpy 验证了这一点.

The problem may be that Clear is not doing what you think it is. Clear simply marks the List as being empty without resizing the internal array that it uses behind the scenes. It will, however, remove all references to the individual BasePopulation instances. So if no other data structure has a reference to them they will be eligible for garbage collection. But, it will not reduce the size of the List directly. I just verified this using ILSpy.

你有两个选择.

  1. 设置 Population = null.这将取消整个对象实例的根,使其符合垃圾回收条件.

  1. Set Population = null. This will unroot the entire object instance making it eligible for garbage collection.

在这个 List 上调用 TrimExcess.这将调整内部数组的大小.

Call TrimExcess on this List. This will resize the internal array.

这篇关于C# 中的大列表使用了多少空闲内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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