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.
问题:
回答1:
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.
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.
回答2:
So then why null it? This will do the trick for you, letting the old list stay on the heap for garbage collection, while existing methods that access the list can continue to function on a new, empty list:
this.FooList = new List<Foo>();
回答3:
After the Reset
call I would leave the object in the same state it was in after the constructor had been called.
If your constructor created a new empty List
then do that. If not make it null
.