none
How instantly free up the memory RRS feed

  • Question

  • 1) in one of my routine i used many list and dataset. i populated those with high volume of data. when event used end then clear memory for list like

    list1 = null and GC.Collect() in my routine but i am not sure that memory occupied by List1 is instantly clear or will be clear later. please share the knowledge.

    2) in case of dataset i clear like

    dataset1.Dispose()

    dataset1=null

    GC.Collect()

    but i am not sure that memory occupied by dataset1 is instantly clear or will be clear later. please share the knowledge.

    3) if i call GC.Collect() several time in my one routine does degrade the performance of my application ?

    i found one link which said best option to release memory for list this way

    first clear List and then call TrimExcess. is it the right one ?

    i used like list1=null & GC.Collect()

    which one is best to clear memory for list instantly ?

    please see my code below which works well.

            private void button2_Click(object sender, EventArgs e)
            {
                var before = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
    
                List<string> lst1 = new List<string>();
    
                for (int i = 0; i <= 1000000; i++)
                {
                    lst1.Add("Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test ");
                }
    
                var after = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
    
                lst1.Clear();
                lst1.TrimExcess();
    
                var current = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
            }
    please share best option to clear memory for list & dataset instantly. thanks

    Thursday, April 11, 2019 7:34 PM

Answers

  • lst1.Clear(); deletes all of the string objects (150MB in your example), and makes that memory available for GC.  It leaves the list with 1,000,000 null references.  lst1.TrimExcess() reallocates the list so it contains 0 references, freeing up another 8MB or so.  The List object itself still exists, exactly as it did after you called "new".  Setting lst1 = null; does both of those operations, PLUS frees up the few dozen bytes that an empty List object occupies.

    GC.Collect can take a rather long time.  In general, the runtime is pretty good ad judging when it is a good time to do a garbage collection.  There's no reason to call GC.Collect unless you have freed up a bunch of objects AND you now need to allocate a bunch more stuff.

    I suspect you are guilty of premature optimization here.  You should get your code to work first, and then see if you have memory or performance problems.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Thursday, April 11, 2019 10:49 PM