Clearing a private collection or its null value?

I have a mutable class that 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 to a new list? Please note that the list is not public and is used only by the class itself. Therefore, the assignment of a new list should make the old unattainable. Since the Clear() method is an O (n) operation , I am interested in the disadvantage of simply assigning a new list over it.

+6
source share
3 answers

The only drawback I can think of is that if you need to use the list again, you will have to allocate new space for it.

To drop this will simply make the list and its contents (in the absence of other links) eligible for the GC. A cleanup will delete the items, but leave the allocated memory.

Personally, I am inclined to exclude this thing, even if I need it, the size will be completely resized.

Update: In connection with the comments below, you indicate that these objects will be managed in the object pool. I would suggest creating a small console application to get the final answer. Now the discussion moves on to the specifics of your implementation and the intended use of the pool of objects, which can easily change the answer.

Generally speaking, if you have lists that do not change in length and will always be necessary, I would use Clear to avoid allocating new memory for the lists. If the length of the list is subject to significant changes, or the use is sometimes scarce, I would prefer to reset it to regain memory and get some minor advantages due to lazy list creation.

+5
source

So why is this needed? This will help you by letting the old list remain on the garbage collection heap, while existing list access methods can continue to function in the new empty list:

 this.FooList = new List<Foo>(); 
0
source

After calling Reset I left the object in the same state it was in after the constructor was called.

If your constructor created a new empty List , then do it. If not make it null .

0
source

Source: https://habr.com/ru/post/921647/


All Articles