JohnnyBravo75
JohnnyBravo75

Reputation: 353

How do i discover the memory consumption of objects in code

I want evaluate object sizes in memory via Diagnostics, but I´m a litte confused, how can the size of all objects in memeory be higher than the total memrory size ?

The GC.GetTotalMemory() gives me a other value (lower) then when I loop through all objects on the heap and summarize them:

TotalSize: 22236, ObjectSize: 452999 And when i look in taskmanager the Memory consumption has another differnent value (11,4 MB)?

So what is the real memory consumption? My target is to track our objects and the consumption.

What I´m doing wrong?

    private static void EvaluateMemoryConsumption()
    {
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 
        GC.Collect();
    
        long totalMemory = GC.GetTotalMemory(forceFullCollection: false);
        long totalObjSize = 0;
    
        using (var dataTarget = DataTarget.AttachToProcess(Process.GetCurrentProcess().Id, suspend: false))
        {
            using (var runtime = dataTarget.ClrVersions[0].CreateRuntime())
            {
                foreach (var segment in runtime.Heap.Segments)
                {
                    foreach (var obj in segment.EnumerateObjects())
                    {
                       totalObjSize += (long)obj.Size;                          
                    }
                }
            }
        }
    
        Console.WriteLine($"TotalSize: {totalMemory}, ObjectSize: {totalObjSize}");   
        
        // TotalSize: 22236, ObjectSize: 452999
    }

Upvotes: 0

Views: 31

Answers (0)

Related Questions