Hacker News new | ask | show | jobs
by buybackoff 13 days ago
It's far from straightforward. And I need a special mode, eg during application start it may generate a lot of garbage, I want that collected, but then continue with idle GC. With an option to collect overnight, or when too much is allocated, but in controlled way.
1 comments

This pattern isn't far from what a videogame sometimes needs to run a level: load a lot of data, generate a lot of garbage, try to collect all the garbage after load but before gameplay, then keep the GC from running again.

In C# you get most of that by calling `GC.Collect()` when you know you've finished loading and should be in a steady state. (I've seen non-games do it after application start as well, though in an enterprise application with full Server GC and plenty of RAM it feels more like a superstitious call than a necessary one.) Then in your "idle state" you can just try to avoid creating garbage. Games often use object pools aggressively, making sure most objects it needs are LOH/Gen2 and a few other "no allocation"/stack allocation-only approaches in the middle of a level.

You can try to ask the GC nicely with `GC.TryStartNoGCRegion()` during a section of your code but it's not necessarily a good idea and a lot of caveats apply.

But also, a lot of what you are asking for is sort of already what the default GC is optimized for by being a generational mark-and-sweep GC. It's tuned for bursts like application startup generating a lot of quick garbage that never leaves Gen0 and fast "arena sweeps". It's tuned for eventually reaching an Idle state where most of your objects are long-lived and hanging out in Gen2 and very rarely even checked to be collected.