.net does ArrayList.Clear free up memory?

I have a densely populated arraylist that I want to clean and reuse. If I clear it, will it free this previously used memory?

I should also mention that arraylist is a private read-only field for the class, which still has a lot of active work after I first used arraylist. Therefore, I can’t wait for garbage collection after the class goes beyond.

Is the Clear method fast enough? Or should I destroy and create a new arraylist?

Question update:

If I have a field declared this way (thanks to John's advice)

/// <summary> /// Collection of tasks. /// </summary> private List<Task> tasks = new List<Task>(); 

then I populate it ... (strongly)

Now, if instead of cleaning and trimming, I can just call:

 tasks = new List<Task>(); 

Would this be recommended?

+7
arraylist c #
source share
2 answers

Depending on what expresses your intention better. Do you really want a new list? If so, create a new one. If you conceptually want to use the same list, call Clear .

The documentation for ArrayList states that Clear retains its original capacity - so you will still have a large array, but it will be filled with zeros instead of referencing the previous elements:

Capacity remains unchanged. To reset the capacity of an ArrayList , call TrimToSize or set the Capacity property directly. Trimming an empty ArrayList sets the ArrayList capacity to its default value.

Any reason you are using an ArrayList rather than List<T> ?

+16
source share

If you really want the memory free, set it to null and call the garbage collector. Then create a new ArrayList. If you set it to null and then create a new one, it will end up with garbage collection when additional memory is needed. In addition, I am the second generic collection. This has been a long time since I used ArrayList.

+3
source share

All Articles