清除私人收藏或将其设置为空? [英] Clearing a private collection or setting it to null?

查看:98
本文介绍了清除私人收藏或将其设置为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有拥有私人列表℃的可变类; T>在字段。在复位()我的课的方法,应使用其清除()方法,我清除列表,或只是分配该领域一个新的列表?注意,列表是不公开的,并且只能由类本身使用。因此,分配一个新的列表应该做旧的不可达。因为清除()方法的是一个O(n)操作,我不知道什么是它分配了它一个新的列表下行

I have a mutable class which has a private List<T> field inside. In the Reset() method of my class, should I clear the list using its Clear() method or just assign its field a new list? Note that the list is not public and is only used by the class itself. So assigning a new list should make the old one unreachable. Since the Clear() method is an O(n) operation, I wonder what is the downside of just assigning a new list over it.

推荐答案

我能想到的唯一的缺点是,如果你需要再次使用的列表,你必须为它分配新的空间。

The only downside I can think of is if you need to use the list again you'll have to allocate new space for it.

归零它只是使列表及其内容(假设没有其他引用)资格GC。清除它会删除的项目,但保留已分配的内存。

Nulling it will just make the list and its content (assuming no other references) eligible for GC. Clearing it would remove the items but leave the memory allocated.

我个人倾向于空的,即使我再需要它的东西,规模将完全改变。

Personally I tend to null the thing as even if I need it again, the size will have changed completely.

更新:用于修饰下面的评论,你的国家,这些对象将在对象的池来管理。我建议设立一个小型的分析控制台应用程序,以获得最终的答案。讨论目前正加紧到您的实现和对象池,它可以很容易地改变答案的预期用途的细节。

Update: Pertaining to the comments below, you state these objects will be managed in a pool of objects. I would advise creating a small profiling console app to get the final answer. The discussion is now stepping into the specifics of your implementation and the intended usage of the object pool, which could easily change the answer.

一般来说,如果你有列出了长度不发生大的变化,总是会被要求,我会使用清除来避免名单分配新的内存。如果列表长度容易了很大的改变,或使用有时是稀疏的 - 我赞成以回收内存,并获得通过的名单延迟实例一些小的好处归零它

Generally speaking, if you have lists that don't change in length much and are always going to be required, I would use Clear to avoid allocating new memory for the lists. If the list length is liable to a lot of change, or usage is sometimes sparse - I would favour nulling it in order to reclaim memory and gain some minor benefits via lazy instantiation of the lists.

这篇关于清除私人收藏或将其设置为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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