Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net does ArrayList.Clear free up memory?

Tags:

c#

.net

arraylist

I have a heavily populated arraylist, which I want to clear and reuse. If I clear it will it free up that previously used memory?

I should also mention that the arraylist is a private read only field of a class that still has lots of active work to do after I use the arraylist first time round. So I can't wait for garbage collection after class goes out of scope.

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

Question update:

If I have field declared like this (thanks to Jon's advice)

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

then I populate it.... (heavily)

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

tasks = new List<Task>(); 

Would this be recommended?

like image 474
JL. Avatar asked Jan 13 '10 20:01

JL.


People also ask

Does ArrayList clear free memory?

The answer to your question, it will not FREE the memory. It will just remove all the object references .

What does ArrayList clear do?

The clear() method of ArrayList in Java is used to remove all the elements from a list.

What is the difference between ArrayList Clear () and removeAll () methods?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

How do you empty an ArrayList?

Method 1: Using clear() method as the clear() method of ArrayList in Java is used to remove all the elements from an ArrayList. The ArrayList will be completely empty after this call returns.


1 Answers

Do whichever expresses your intention better. Do you actually want a new list? If so, create a new one. If you conceptually want to reuse the same list, call Clear.

The documentation for ArrayList does state that Clear retains the original capacity - so you'll still have a large array, but it'll be full of nulls instead of reference to the previous elements:

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

Any reason you're using ArrayList rather than List<T> by the way?

like image 95
Jon Skeet Avatar answered Sep 30 '22 17:09

Jon Skeet