Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET, get memory used to hold struct instance

Tags:

c#

It's possible to determine memory usage (according to Jon Skeet's blog) like this :

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'm running x64 machine). Consider we change Point declaration from class to struct. How then to determine memory used? Is is possible at all? I was unable to find anything about getting stack size in .NET

P.S

Yes, when changed to 'struct', Point instances will often be stored on Stack(not always), instead of Heap.Sorry for not posting it first time together with the question.

P.P.S

This situation has no practical usage at all(IMHO), It's just interesting for me whether it is possible to get Stack(short term storage) size. I was unable to find any info about it, so asked you, SO experts).

like image 303
illegal-immigrant Avatar asked Jun 16 '11 18:06

illegal-immigrant


2 Answers

You won't see a change in GetTotalMemory if you create the struct the way you did, since it's going to be part of the thread's stack, and not allocated separately. The GetTotalMemory call will still work, and show you the total allocation size of your process, but the struct will not cause new memory to be allocated.

You can use sizeof(Type) or Marshal.SizeOf to return the size of a struct (in this case, 8 bytes).

like image 139
Reed Copsey Avatar answered Oct 24 '22 04:10

Reed Copsey


There is special CPU register, ESP, that contains pointer to the top of the stack. Probably you can find a way to read this register from .Net (using some unsafe or external code). Then just compare value of this pointer at given moment with value at thread start - and difference between them will be more or less acurate amount of memory, used for thread's stack. Not sure if it really works, just an idea :)

like image 23
Victor Haydin Avatar answered Oct 24 '22 04:10

Victor Haydin