I have a situation where garbage collection is a major bottleneck in my application. What happens is there are certain objects that are expensive to clean up -- they contain arrays of other objects. So what I thought I'd try is recycling the objects. More often than not, I don't know when they are free to recycle, so I figured I'd override Finalize, at which point I'd put them in a cache to be used next time I need to create one. Problem solved. Or is it?
Asked
Active
Viewed 46 times
0
-
no I'm afraid not - better to keep them in your cache all the time and use a flag to indicate if they are free (or move them into a *used* hashset or whatever) - see [here](https://msdn.microsoft.com/en-us/library/system.object.finalize%28v=vs.110%29.aspx) please – Random Dev Feb 21 '16 at 14:09
-
This is a well studied problem. Google for ".net cache finalizer". Or replace "cache" with "object pool". Basically, this is bad because the GC does not have to goal of maintaining efficient cache behavior for you. It might over or undercollect. To clarify: This scheme can work but it's more a solution of last resort. – usr Feb 21 '16 at 14:16
-
Thanks for your responses. It looks like the best I can do is to cache only instances that I know are no longer needed, and let the rest be garbage collected. – Len White Feb 21 '16 at 14:34
1 Answers
1
This is a well studied problem. Google for ".net cache finalizer". Or replace "cache" with "object pool". Basically, this is bad because the GC does not have to goal of maintaining efficient cache behavior for you. It might over- or under-collect. To clarify: This scheme can work but it's more a solution of last resort.
Also, you might want to somehow prove these objects to be the true reason for your performance problems. There is no GC profiler for .NET that allows you to pinpoint the perf contribution of individual objects. Maybe you can quickly hack together this object pool in a dirty way and measure the difference.

usr
- 168,620
- 35
- 240
- 369