Incremental Garbage Collection in Unity 2019 – Overview

Uploaded by Unity
Share: Twitter Facebook
Learn more about Incremental Garbage Collection: https://ole.unity.com/IncrementalGC

Check out Performance Tools on the Asset Store: https://ole.unity.com/performance-tools

Check out our webpage for courses: https://ole.unity.com/unitycourses

The C# language uses managed memory with automated garbage collection, meaning that it uses an automatic method of tracking objects in memory and releasing the memory of any object which is no longer needed (See our documentation for more info).

The benefit of this is that you generally don’t need to manually keep track of releasing any memory which you don’t need anymore because the garbage collector will automatically do that for you, which makes your work easier and also removes a big source of potential bugs. The downside is that the garbage collector takes some time to do its work, and this may happen in moments when you would rather not want to spend time on this.

Unity uses the Boehm–Demers–Weiser garbage collector which is a stop-the-world garbage collector, meaning that whenever it needs to perform garbage collection, it will stop the running program, and only resume normal execution once it has finished all its work. This can cause delays in the execution of the program at somewhat arbitrary moments, which can take anywhere between less than 1 and several 100 milliseconds, depending on how much memory the garbage collector needs to process and on the platform the program is running on.

Now, obviously, for real-time applications like games, this can become quite a big issue, as it isn’t possible to sustain a consistent frame rate as required for smooth animation if the program’s execution can be arbitrarily suspended by the garbage collector. These interruptions are also known as GC spikes, as they will show as spikes in an otherwise smooth profiler frame time graph. Usually, developers try to work around this issue by writing their code to avoid creating “garbage” memory while running the game, so the garbage collector has less work to do – but this isn’t always possible or easy.

Enter Incremental Garbage Collection. With Incremental GC, we still use the same Boehm–Demers–Weiser GC, but we run it in an incremental mode, which allows it to split its work into multiple slices. So instead of having a single long interruption of your program’s execution to allow the GC to do its work, you can have multiple, much shorter interruptions. While this will not make the GC faster overall, it can significantly reduce the problem of GC spikes breaking the smoothness of the animation by distributing the workload over multiple frames.