Matthew
Matthew

Reputation: 10444

When is it more appropriate to assign a new list than to .Clear() an existing list?

Given a list:

List<myType> myList = new List<myType>();

with the collection contents modified at runtime....

To clear the list, I have seem examples which suggest using

myList = new List<myType>();

rather than

myList.Clear();

I can think of a number of reasons why I would prefer one over the other but are there any other good benchmarks or guidelines as to when one method is preferable to the other?

Upvotes: 4

Views: 177

Answers (3)

DCShannon
DCShannon

Reputation: 2614

Be careful using Clear. It modifies the actual list. If you have another reference to that same list somewhere, perhaps under a different name, you may have unexpected results.

For example:

List<int> one = new() { 1, 2, 3 };
List<int> two = one;
one.Clear(); // two is now also empty

List<int> three = new() { 1, 2, 3 };
List<int> four = three;
three = new(); // four still has values in it

Therefore, in order to avoid unintended consequences, I prefer to make a new List as the usual practice. Clear can be used in certain cases, just make sure you really want to clear everything that it clears.

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 134015

If a list is large (80 kilobytes or more), then it's going to be stored on the large object heap. The official guidance for the LOH is to re-use objects there as much as possible in order to reduce heap fragmentation. The LOH isn't compacted like the regular heap is.

For smaller lists, I've found that it's often faster overall to create a new one than it is to call Clear. This isn't always true, so you're probably best off testing it both ways in your applications.

If you call Clear, it just sets all of the items in the list to their default values and sets Count to 0. It does not change the list's capacity. So calling Clear will not change the amount of memory allocated to the collection. If you want to clear the list and reduce its size, call Clear and then TrimExcess.

One problem you'll run into if you're not careful is aliasing. If you have multiple objects that refer to the same list, creating a new list doesn't remove those other references. So then you end up with two lists. Just something to think about.

All told, I don't think there's a particular "best practice" for this. I've found that sometimes it's good to use Clear and sometimes it's best to allocate a new list.

Upvotes: 3

tsells
tsells

Reputation: 2771

When you are binding to the list object and have references to it from other areas of code - then use the clear method. If you have no references and are not bound then creating a new object would be appropriate.

Upvotes: 2

Related Questions