C ා memory allocation performance test

1, In 64 bit application, the performance of C ා object and structure memory allocation is tested. The test results are as follows

Two. Conclusion
1. GC.GetTotalMemory gets not physical memory, but the memory counted by Runtime itself.
2. When creating a new array, instead of allocating physical memory immediately, virtual memory is allocated.
3. Under 64 bit, the object occupies 16 bytes by default (object pointer and synchronous block index). There is no similar content in the structure. If you have to reduce the memory consumption, you can consider using the structure.
4. The allocation of a large number of small objects is time-consuming, which costs 74ms every 1M*32.
5. The total size of 1.6G structure array allocation time is very small, about 200ms.

Three, source code

public class ClassMemory
{
    public int a;
    public float b;
    public double c;

}
public struct StructMemory
{
    public int a;
    public float b;
    public double c;
}


public class MemoryTest
{
    public void DoTest()
    {
        Stopwatch s = new Stopwatch();
        s.Start();
        int minMemoryLen = 100000000;
        long t1 = s.ElapsedMilliseconds;
        long m1 = GC.GetTotalMemory(false);

        ClassMemory[] minClassArr = new ClassMemory[minMemoryLen];
        long m2 = GC.GetTotalMemory(false);
        long t2 = s.ElapsedMilliseconds;


        for (int i=0;i< minMemoryLen; i++)
        {
             minClassArr[i] = new ClassMemory();
        }
        long m3 = GC.GetTotalMemory(false);
        long t3 = s.ElapsedMilliseconds;



        long m4 = GC.GetTotalMemory(false);
        long t4 = s.ElapsedMilliseconds;
        StructMemory[] minStructArr = new StructMemory[minMemoryLen];
        long m5 = GC.GetTotalMemory(false);
        long t5 = s.ElapsedMilliseconds;


        for (int i = 0; i < minMemoryLen; i++)
        {
            minStructArr[i] =  new StructMemory();
        }

        long m6 = GC.GetTotalMemory(false);
        long t6 = s.ElapsedMilliseconds;



        for (int i = 0; i < minMemoryLen; i++)
        {
            minStructArr[i] = new StructMemory();
        }

        long m7 = GC.GetTotalMemory(false);
        long t7 = s.ElapsedMilliseconds;


        Console.WriteLine((t2 - t1) + " " + (t3-t2));
        Console.WriteLine((m2 - m1) + " " + (m3 - m2));

        Console.WriteLine((t5 - t4) + " " + (t6 - t5) + " " + (t7 - t6));
        Console.WriteLine((m5 - m4) + " " + (m6 - m5) + " " + (m7 - m6));

    }
}

4, Output results

Posted by plowter on Thu, 02 Jan 2020 07:47:58 -0800