We’re still hard at work bringing the latest .NET technology to Unity users. As one team member leading this effort,
Josh Peterson is excited to share further progress. Part of the work involves making existing Unity code work with the .NET CoreCLR JIT runtime, including a highly performant, more advanced, and more efficient garbage collector (GC).
This blog post from last year covers recent changes the team has made to allow the CoreCLR GC to work hand in hand with Unity engine native code. It starts at a high level, then gets into more technical details.
A bit about garbage collectors
Memory allocation done in the C# language is managed by a garbage collector. Anytime memory allocation is required, the code allocating that memory can ignore the memory when it is no longer used. The GC will helpfully come by later and recycle that memory for other code to use.
Unity currently uses the Boehm GC, which is a conservative, non-moving GC. It will scan all thread stacks (including managed and native code) looking for managed objects to collect and once it allocates a managed object, the location of that object will never move in memory.
.NET uses the CoreCLR GC, which is a precise, moving GC. It tracks allocated objects only in managed code, and will move them in memory to improve performance. This allows the CoreCLR GC to work with much less overhead and provide your game with better performance characteristics.
Both GCs are excellent at what they do, but they place different requirements on that code using them. The Unity engine and editor code have been developed based on the requirements of the Boehm GC, so to use the CoreCLR GC, we need to make a number of changes to the Unity code, including to the custom marshaling tools Unity wrote – the bindings generator and the proxy generator.
For more information, read the full blog.