我正在制作游戏,我想测量一下我正在测试的概念占用多少内存。我知道它不会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);
}
}
}
答案 0 :(得分:1)
不是真的,因为当GC
释放内存时你无法控制,而且你的测量之间可能会发生这种情况。另外,正如我所理解的那样,GC
不会计算位于堆栈内存而不是堆上的结构。
可能更准确地总结一下你自己知道每件物品占用多少内存。