Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a private collection or setting it to null?

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.

like image 650
Şafak Gür Avatar asked Jul 30 '12 07:07

Şafak Gür


People also ask

Can collections be null?

In most cases null is nothing (except in SQL). An empty collection is something, albeit an empty something. If you have have to choose one or the other, I would say that you should tend towards an empty collection rather than null. But there are times when an empty collection isn't the same thing as a null value.

Should I return null or empty array?

Some functions return arrays, which appear like a pointer to an object. However, if a function has the option of returning an array or indicating that a valid array is not possible, it should not return NULL . Instead, the function should return an empty array.

Can collections null C#?

An object collection such as an IEnumerable<T> can contain elements whose value is null.

How do you clear a list in C#?

To empty a C# list, use the Clear() method.


1 Answers

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.

like image 158
Adam Houldsworth Avatar answered Sep 26 '22 08:09

Adam Houldsworth