0

Consider this simple code:

class Program
{
    static List<Data> listData = new List<Data>();
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            Data newData = new Data();
            newData.num1 = i;
            newData.num2 = i * 5;
            listData.Add(newData);
        }
        Console.ReadLine();
    }
}

class Data
{
    public int num1 { get; set; }
    public int num2 { get; set; }
}

For some reason, when profiling memory for this code, it shows that there are 2 Data[] objects in memory (which i assume are listData objects): dotMemory 4 ss Can anyone explain why?

user1307346
  • 715
  • 3
  • 9
  • 14

2 Answers2

3

No, you don't have an extra List<Data> in memory, you have two Data[] arrays. Which are the underlying storage for the List<> object you created.

List<> starts out with an empty array, the first Add() call creates a Data[] array that can fit 4 elements. Which runs out on the fifth Add() call, it now creates a Data[] array that's double the size, it can store 8 elements. Your memory profiler still sees the Data[] array that's garbage, the GC hasn't run yet.

You can use the Capacity property to optimize this. Lots more details in this post.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
2

I think you can count on the garbage collector to do its job... don't worry about it (I don't have enough reputation to post this as comment)

o.z
  • 1,086
  • 14
  • 22