質問

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);
        }
    }
}
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top