4

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
  • 1
    If you do List<int> mylist = new List<int>();, then you are creating a new list ready to use. No need to clear it, it's ready to use, just access it through your variable (mylist) that holds a reference to it. If you reassign the list (mylist = new List<int>();), then the old list is no longer referenced by your code (if there are no other references to that list, then it's ready for Garbage Collection) and you create a new list. Your mylist variable now holds a reference to that new list, and it's ready to use in the same way.
    – Flydog57
    Jan 10, 2019 at 19:24
  • Clearing will help will unnecessary allocation and unnecessary GC collection but will leave more memory allocated ... so the question is primarly opition based: speed vs memory usage
    – Selvin
    Jan 10, 2019 at 19:26
  • 3
    The only other real factor is are there other shared references being held to that list. If you clear it those references continue to use the shared list. By newing it this part of the code abandons the old list and starts using a new one so changes made after that point would not be reflected in the other shared references.
    – Igor
    Jan 10, 2019 at 19:32

3 Answers 3

7

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.

2

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.

2
  • 1
    while method 1 just clears the internal array so the garbage collector can reclaim the memory not true first method will not cause any GC work edit: ... for List itsef - of course if List will store some other object than primitives it would - but again, for List<int> there will be not GC work
    – Selvin
    Jan 10, 2019 at 19:42
  • and about Array.Clear it's prolly simple RtlSecureZeroMemory(*_items, size*sizeof(T)) call on windows platform (for primitives)... when "reallocation" is alloc+create new List instance, alloc+create all fields of List class ... and alloc in .net is not simple RtlAllocateHeap call ... you have to create pointer for GC, etc. etc. (again for List<int>)
    – Selvin
    Jan 10, 2019 at 19:51
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.