我写了这个小测试程序:
using System;
namespace GCMemTest
{
class Program
{
static void Main(string[] args)
{
System.GC.Collect();
System.Diagnostics.Process pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
long startBytes = pmCurrentProcess.PrivateMemorySize64;
double kbStart = (double)(startBytes) / 1024.0;
System.Console.WriteLine("Currently using " + kbStart + "KB.");
{
int size = 2000000;
string[] strings = new string[size];
for(int i = 0; i < size; i++)
{
strings[i] = "blabla" + i;
}
}
System.GC.Collect();
pmCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
long endBytes = pmCurrentProcess.PrivateMemorySize64;
double kbEnd = (double)(endBytes) / 1024.0;
System.Console.WriteLine("Currently using " + kbEnd + "KB.");
System.Console.WriteLine("Leaked " + (kbEnd - kbStart) + "KB.");
System.Console.ReadKey();
}
}
}
发布版本中的输出是:
Currently using 18800KB.
Currently using 118664KB.
Leaked 99864KB.
我假设 GC.collect 调用将删除分配的字符串,因为它们超出了范围,但看起来并没有。我不明白,也找不到解释。也许这里有人吗?
谢谢,
亚历克斯
您正在查看私有内存大小 - 托管堆将扩展以容纳字符串,但当字符串被垃圾收集时,它不会将内存释放回操作系统。相反,托管堆会更大,但有大量可用空间 - 因此,如果您创建更多对象,则不需要扩展堆。
如果你想看内存used在托管堆中,查看GC.GetTotalMemory http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory(v=VS.100).aspx。请注意,由于垃圾收集的复杂性,所有这些都存在一定程度的混乱。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)