c# clearing a list vs assigning a new list to existing variable

Viewed 4365

I am learning C#.

If I first make a variable to hold a list.

List<int> mylist = new List<int>();

Say I did some work with the list, now I want to clear the list to use it for something else. so I do one of the following:

Method 1:

mylist.Clear();

Method 2:

mylist = new List<int>();

The purpose is just to empty all value from the list to reuse the list.

Is there any side effect with using method2. Should I favor one method to the next.


I also found a similar question, Using the "clear" method vs. New Object I will let other readers decide what's best for their own use case. So I won't pick a correct answer.

3 Answers

Using method 2 could result in unexpected behaviour within your program depending on how you are using the list.

If you were to do something like:

List<int> myList = new List<int> { 1, 2, 3 };

someObj.listData = myList;

myList = new List<int>(); // clearing the list.

the data in "someObj" will still be 1,2,3.

However, if you did myList.clear() instead, then the data in "someObj" would also get cleared.

An additional thought I just had. If you have dangling references to the original list, and reassign the variable using new in order to clear it, the GC will never clean up that memory. I would say it's always safer to use the .clear() method if you need to empty the contents of a list.

Method 2 will cause a reallocation while method 1 just clears the internal array so the garbage collector can reclaim the memory:

From source:

// Clears the contents of List.
public void Clear() {
    if (_size > 0)
    {
        Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
        _size = 0;
    }
    _version++;
}

https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,2765070d40f47b98

I think reallocating is going to be less expensive than clearing the array. Either way the performance is probably negligible unless you are doing some real super intensive work. In that case you would probably consider using a data structure that is faster than a list anyways.

Is there any side effect with using method2? Yes. First, theres an allocation of a new object, Second, the first list might get collected the next time the garbage collector collects.

Should I favor one method to the next.? You should favor the first method, since it expresses your intention ,to clear the list, more clearly.

Related