C# Object Size Overhead

前端 未结 3 660
日久生厌
日久生厌 2021-02-04 14:59

I am working on optimization of memory consuming application. In relation to that I have question regarding C# reference type size overhead.

The C# object consumes as ma

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 15:14

    There is an article online with the title "The Truth About .NET Objects And Sharing Them Between AppDomains" which shows some rotor source code and some results of experimenting with objects and sharing them between appdomains via a plain pointer.

    http://geekswithblogs.net/akraus1/archive/2012/07/25/150301.aspx

    • 12 bytes for all 32 Bit versions of the CLR
    • 24 bytes for all 64 bit versions of the CLR

    You can do test this quite easily by adding millions of objects (N) to an array. Since the pointer size is known you can calculate the object size by dividing the value of

    var intial = GC.GetTotalMemory(true)
    const int N=10*1000*1000;
    var arr = new object[N];
    for(int i=0;i

    to get an approximate value on your .NET platform.

    The object size is actually a define to allow the GC to make assumptions about the minimum object size.

    \sscli20\clr\src\vm\object.h
    
    //
    // The generational GC requires that every object be at least 12 bytes
    // in size.   
    #define MIN_OBJECT_SIZE     (2*sizeof(BYTE*) + sizeof(ObjHeader))
    

    For e.g. 32 bit this means that the minmum object size is 12 bytes which does leave a 4 byte hole. This hole is empty for an empty object but if you add e.g. an int to your empty class then it is filled and the object size stays at 12 bytes.

提交回复
热议问题