Page 1 of 1

System.Collections.Generic.List<>

Posted: Mon Mar 13, 2006 9:15 pm
by scot.prichard@med.ge.com
Why does the list appear as a leak between MemSnapShot 2/3 but the array between MemSnapShot 1/2 does not?
-----------
using System;
using System.Collections.Generic;
using System.Text;

namespace test0313
{
class Program
{
private class Leak
{
}

private static void TestArray()
{
Leak[] array = new Leak[10];
for (int i = 0; i < 10; i++)
array = new Leak();

for (int i = 0; i < 10; i++)
array = null;
array = null;
}

private static void TestList()
{
List<Leak> list = new List<Leak>();
for (int i = 0; i < 10; i++)
list.Add(new Leak());

for (int i = 0; i < 10; i++)
list = null;
list.Clear();
list.TrimExcess();
list = null;
}

static void Main(string[] args)
{
SciTech.NetMemProfiler.MemSnapShot memSnapshot0 = SciTech.NetMemProfiler.MemProfiler.FullSnapShot();
TestArray();
SciTech.NetMemProfiler.MemSnapShot memSnapshot1 = SciTech.NetMemProfiler.MemProfiler.FullSnapShot();
TestList();
SciTech.NetMemProfiler.MemSnapShot memSnapshot2 = SciTech.NetMemProfiler.MemProfiler.FullSnapShot();
}
}
}

Posted: Mon Mar 13, 2006 9:49 pm
by Andreas Suurkuusk
When you create the List<Leak> instance in the TestList method, the class constructor creates an empty Leak array and stores it in a static field (List<T>._emptyArray). The empty array is used by the default constructor and when setting Capacity to 0. So this is not a leak; if you run TestList more times, no more Leak arrays will be created.