Search code examples
c#collectionsgarbage-collectiondynamic-memory-allocation

.net List<T> Trim Excess


Consider this situation: Form1 builds a List object with tons of elements in it. Then, it has to pass this collection to Form2 via a parameter.

I want to clear everything related to the collection in Form1 after making a hard copy of it in Form2. Let Col1 be the identifier for the collection in Form1.

Since Col1 is passed by reference via parameters, I'm calling Col1.Clear() to clear it of its elements, and then Col1.TrimExcess() to reduce its actual size to 0, so it doesn't keep track of tons of null values.

My intention is to clear all used memory as quickly as possible. Col1.TrimExcess() should clear all used memory, but I'm curious whether Col1 = null would work better in my (or most) case?


Solution

  • I'm guessing you are doing this so you can "prepare" stuff in form1, then pass the ready contents to Form2 in order to avoid some kind of lagging or something, am I correct? In any case, there are a couple of issues to consider:

    As Tim Schmelter points out, adding a reference to a list "X" from form 2 does not create a copy - only a new reference to X. Removing the reference to X from form 2 should also not reduce memory, since X will still exist - there will just be one thing less with a pointer to it. If you do create a hard copy of the list however, then you might indeed save some memory by removing all referenced to the original list and the data it contains. (Note however, that deep copying a list is not always straight foreward...)

    As for weather to use clear() and TrimExcess(), I would generally assume that these are built in for a good reason, and expect them to perform quite well. In any case, I highly doubt that they will affect the speed of your code in any significant way.

    Also, if you should choose to use col = null, you will end up with a variable with a null value (obviously...), while the other option will end up with an empty (but non-null) list. If I'm not mistaken, the equivalent of trimming the list to zero length "manually" is not to set it to null, but to point it to a new (empty) list: col = new List(), but I doubt that would save you any CPU cycles.

    In short, I would recommend you go ahead like you started, and use the built in methods.