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);
        }
    }
}
3
  • Why do you want to know the size? What are you trying to accomplish? Apr 22, 2014 at 0: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, 2014 at 1: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. Apr 22, 2014 at 1:32

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.