1

I'm making a game and I'd like to measure how much memory would be occupied by a concept I'm testing. I recognize it wouldn't be 100% accurate, but does this give me a reliable ballpark figure on the size of the object?

using System;
using System.Collections.Generic;

namespace Sandbox
{
    public class Program
    {
        public static void Main(string[] args)
        {

            long startMemory = GC.GetTotalMemory(true);
            Dictionary<short, KeyValuePair<short, short>> values = new Dictionary<short, KeyValuePair<short, short>>();
            for (short i = 0; i < 3000; i++)
            {
                values.Add(i, new KeyValuePair<short, short>(short.MaxValue, short.MaxValue));
            }
            Console.WriteLine(GC.GetTotalMemory(true) - startMemory);
        }
    }
}
i3arnon
  • 113,022
  • 33
  • 324
  • 344
BenR
  • 2,791
  • 3
  • 26
  • 36
  • Why do you want to know the size? What are you trying to accomplish? – Brian Rasmussen Apr 22 '14 at 00:19
  • @BrianRasmussen What I'm trying to accomplish is irrelevant, knowing how to test the memory size of an object is a valuable thing to know. But I'm testing a game concept that might require memory storage of hundreds of thousands of vector points. I've tested several methods to see which occupies the least amount of memory and now I want to make sure my measurements are generally accurate. – BenR Apr 22 '14 at 01:24
  • 1
    If handling memory explicitly is important for some reason, .NET might not be the best choice as by design the runtime doesn't give you the necessary tools to dig into the details. FWIW if you do want to know the size of managed objects, the SOS debugger extension or a memory profiler is probably your best option. – Brian Rasmussen Apr 22 '14 at 01:32

1 Answers1

1

Not really, because you don't control when the GC frees up memory, and it could happen between your measurements. Also, as I understand it the GC won't count structs that sit on the stack memory and not the heap.

It's probably more accurate to sum it up yourself knowing how much memory each item you use occupies.

i3arnon
  • 113,022
  • 33
  • 324
  • 344