开发者

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

开发者 https://www.devze.com 2023-03-30 11:26 出处:网络
Given a list: List<myType> myList = new List<myType>(); with the collection contents modified at runtime....

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消