.NET, get the memory used to store the struct instance

You can determine memory usage (according to Jon Skeet's blog) for example:

public class Program
{
    private static void Main()
    {
        var before = GC.GetTotalMemory(true);

        var point = new Point(1, 0);

        var after = GC.GetTotalMemory(true);

        Console.WriteLine("Memory used: {0} bytes", after - before);
    }

    #region Nested type: Point

    private class Point
    {
        public int X;
        public int Y;

        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }
    }

    #endregion
}

It prints Memory used: 16 bytes(I run the x64 machine). Consider that we change the declaration of Point from a class to a struct. How to determine the memory? Is it possible at all? I could not find anything about getting stack size in .NET.

PS

Yes, when changing to 'struct', Point instances will often be stored in Stack (not always) instead of Heap.Sorry, so as not to publish it for the first time along with the question.

PPS

This situation has virtually no practical use (IMHO). I'm just wondering if it is possible to get the size of the stack (short-term storage). I could not find information about this, so I asked you, SO experts).

+5
3

GetTotalMemory, , , . GetTotalMemory - , .

sizeof () Marshal.SizeOf, ( 8 ).

+4

CPU, ESP, . , .Net( - ). - , . , , :)

+1

, , "" . , , , , , GC, . , .

But understand, this is only "reasonable", not a surety.

Why do you need to know the size of objects? Just curious, as knowing a business reason can lead to other alternatives.

0
source

All Articles