MemoryCache中的项目太大了?

时间:2015-09-18 08:47:57

标签: c# memorycache

我正在尝试理解C#中MemoryCache类的大小调整算法。 我认为一个带有短键(一个字符串)和一个小值(即bool)的项目会占用很少的内存,但我的测试证明我错了。

这是我用来测试它的代码:

Console.WriteLine("Mem before creating Cache:" + GC.GetTotalMemory(true).ToString());
MemoryCache cache = new MemoryCache("testcache");
Console.WriteLine("Mem after creating Cache:" + GC.GetTotalMemory(true).ToString());

long tinyAvg=0;
int sampleSize = 500;
for (var i = 0; i < sampleSize; i++)
{
    var memBefore = GC.GetTotalMemory(true);
    cache.Add(i.ToString() , true, null);
    var memAfter = GC.GetTotalMemory(true);
    var overhead = memAfter - memBefore;
    tinyAvg += overhead;
    //Console.WriteLine("Mem overhead for adding tiny item:" + overhead.ToString());
}
Console.WriteLine("Average for tiny item: " + tinyAvg / sampleSize);

运行此代码,我在缓存中得到平均129字节/项,这对我来说太大了。

请注意,我正在使用GC.GetTotalMemory()进行性能分析。我知道它可能没有给出确切的数字,但粗略估计也足够了。

为什么缓存项对于如此小的键/值对如此之大?有没有办法让它变小?

顺便说一句 - 我知道这是微基准测试,我知道这些天内存很便宜。这是一个代表更大缓存的示例,包含巨大的密钥,数百万个项目和有限的RAM,因此我们需要为此找到解决方案......

谢谢!

0 个答案:

没有答案
相关问题