我写了这个小测试程序:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Release版本中的输出是:
Currently using 18800KB.
Currently using 118664KB.
Leaked 99864KB.
Run Code Online (Sandbox Code Playgroud)
我假设GC.collect调用将删除已分配的字符串,因为它们超出范围,但它似乎没有.我不明白也无法找到解释.也许这里有人?
谢谢,亚历克斯
您正在查看专用内存大小 - 托管堆将扩展为容纳字符串,但是当字符串被垃圾回收时,它不会将内存释放回操作系统.相反,托管堆将更大,但拥有大量可用空间 - 因此,如果您创建更多对象,则不需要堆扩展.
如果要查看托管堆中使用的内存,请查看GC.GetTotalMemory.请注意,由于垃圾收集的复杂性,所有这些都有一定程度的羊毛.