这是衡量对象内存大小的有效方法吗?

时间:2014-04-21 16:41:13

标签: c# .net performance memory xna

我正在制作游戏,我想测量一下我正在测试的概念占用多少内存。我知道它不会100%准确,但是这能给我一个关于物体大小的可靠的大概数字吗?

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

不是真的,因为当GC释放内存时你无法控制,而且你的测量之间可能会发生这种情况。另外,正如我所理解的那样,GC不会计算位于堆栈内存而不是堆上的结构。

可能更准确地总结一下你自己知道每件物品占用多少内存。