开发者

.NET Garbage Collection Tuning for Objects Known to Have a Long Life

开发者 https://www.devze.com 2023-03-07 16:57 出处:网络
I\'m working in a .NET application where we have a very large cache implemented with a Dictionary.I remove things from the cache via a TTL and a reaper that periodically checks for expired items.A giv

I'm working in a .NET application where we have a very large cache implemented with a Dictionary. I remove things from the cache via a TTL and a reaper that periodically checks for expired items. A given common TTL value will be on the order of hours.开发者_C百科 Considering this, is there anything I can do each object as I put it into cache so that I don't have to go through Gen0 and Gen1 each time I want to cache something for hours?

EDIT: I should specify my question better. I understand how .NET garbage collection works and I know it's good at it's job. I agree that in ideal situations, you would want it work work exactly as it was designed. Specifically though, I'd like to know if there is any way to have control over how it works for this exact scenario.


Your object will promote into Gen2 relatively quickly since your Dictionary will always leave it rooted.

There isn't an API that lets you allocate directly into a different generation, but I doubt that this will have a real-world impact on performance, since it really doesn't take long for objects to get promoted if they're staying rooted. Any cache with objects that have multi-hour lifetimes shouldn't be ones that are being allocated frequently, so the savings you'd receive even if this were possible would be trivial.


If the cache is large, you may want to look at pooling the objects in the cache, instead of getting rid of them after a time and putting new ones in. Otherwise what you're doing is making garbage out of objects that have been tucked into a corner of Gen 2, and which the GC may not get around to collecting for a long time. This can lead to an increased memory footprint for the application, caused by objects which are not in use but also not being collected until the GC is put under enough stress to warrant digging them out.

Obviously this is more relevant to the scenario of running this instance for a long time, but if you're throwing things away after a few hours, it sounds like that's what you're doing.

0

精彩评论

暂无评论...
验证码 换一张
取 消