Unity’s garbage collector has the following modes:
GarbageCollector.GCMode
API to take full control of when Unity runs the garbage collector.For information on how to use each of the garbage collection modes, refer to Configuring garbage collection.
Incremental garbage collection spreads out the process of garbage collection over multiple frames. This is the default garbage collection behavior in Unity.
Unity’s garbage collector uses the Boehm-Demers-Weiser garbage collector. By default, Unity uses it in incremental mode, which means that the garbage collector splits up its workload over multiple frames and makes shorter interruptions to your application’s execution.
In non-incremental mode, Unity stops the main CPU thread (stop-the-world garbage collection) in one long interruption to process all objects on the managed heap.
Incremental mode doesn’t make garbage collection faster, but because it distributes the workload over multiple frames, performance spikes related to garbage collection are reduced. These interruptions are called GC spikes because they appear as large spikes in the Profiler window’s frame time graph.
Important: The web platform doesn’t support incremental garbage collection. For more information, refer to Memory in web garbage collection considerations.
The following screenshots from the ProfilerA window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating, or in your game logic. More info
See in Glossary illustrate how incremental garbage collection reduces frame rate problems:
In the top profiling session, the Incremental GC setting is enabled. The application has a consistent 60 fpsSee first person shooter, frames per second.
See in Glossary frame rate, because the garbage collector distributes the garbage collection operation over several frames. The garbage collector uses a small time slice of each frame, indicated by the darker green fringe just above the yellow VSync trace.
The bottom profiling session has the Incremental GC setting disabled, and there’s a GC spike visible. The GC spike interrupts the consistent 60 fps frame rate, and pushes the frame in which garbage collection happens over the 16 ms limit required to maintain 60 fps.
If your application uses VSyncVertical synchronization (VSync) is a display setting that caps a game’s frame rate to match the refresh rate of a monitor, to prevent image tearing.
See in Glossary or Application.targetFrameRate
, Unity adjusts the time it allocates to garbage collection based on the remaining available frame time. This way, Unity can run the garbage collector in the time it spends waiting, and can carry out garbage collection with a minimal performance impact.
Note: If you set the VSync Count to anything other than Don’t Sync (in your project’s Quality settings or with the Application.VSync
property), or you enable the Application.targetFrameRate
property, Unity automatically uses any idle time left at the end of a given frame for incremental garbage collection.
To get more precise control over incremental garbage collection behavior, you can use the Scripting.GarbageCollector
class. For example, if you don’t want to use VSync or a target frame rate, you can calculate the amount of time available before the end of a frame and provide that time to the garbage collector.
For more information, refer to Configuring garbage collection.
Incremental garbage collection might be problematic for your application, because when the garbage collector divides its work in this mode, it also divides the marking phase. The marking phase is the phase in which the garbage collector scans all managed objects to determine which objects are still in use, and which objects it can clean up.
Dividing up the marking phase works well when most of the references between objects don’t change between slices of work. However, when an object reference changes, the garbage collector must scan those objects again in the next iteration. This means that too many changes might overwhelm the incremental garbage collector and create a situation where the marking phase never finishes because it always has more work to do. If this happens, the garbage collector falls back to doing a full, non-incremental collection.
When Unity uses incremental garbage collection, it generates additional code (known as write barriers) to inform the garbage collector when it needs to scan an object whenever a reference changes. This adds some overhead when changing references, which has a performance impact in managed code.
Therefore, there are some situations where you might want to disable incremental garbage collection to improve the performance of your application. When you disable incremental mode, the garbage collector must examine the entire heap when it performs a collection pass.
This is known as stop-the-world garbage collection, because whenever the garbage collector runs, it stops the main CPU thread. It only resumes execution once it has processed all objects on the managed heap, which might lead to GC spikes affecting the performance of your application. This delay might last for hundreds of milliseconds, depending on how many allocations the garbage collector needs to process, and the platform that your application is running on.
The garbage collector is also non-compacting, which means that Unity doesn’t redistribute any objects in memory to close the gaps between objects.
Non-incremental garbage collection is problematic for real-time applications such as games, because it’s difficult for your application to sustain the consistent frame rate that smooth animation requires when the garbage collector suspends your application’s execution.
To disable incremental garbage collection, refer to Configuring garbage collection.
You can use the GarbageCollector.GCMode
API to disable garbage collection at runtime. This prevents CPU spikes, but the memory usage of your application never decreases, because the garbage collector doesn’t collect objects that no longer have any references.
Disabling the garbage collector requires careful memory management, or the managed heap continuously expands until your application runs out of memory, and the operating system shuts it down.
It’s best practice to disable garbage collection during short, performance-critical parts of your application, when you’re able to calculate and control how much memory to allocate. After the performance-critical section is over, re-enable the garbage collector. Profile your project to ensure that you don’t trigger additional managed allocations which might cause the managed heap to get too big.
It’s best practice to only disable the garbage collector for long-lived allocations. For example, you might want to allocate all required memory for a level of your game before it loads, and then disable the garbage collector to avoid performance overhead during the level. After the level is completed and all memory is released, you can then enable the garbage collector again and use System.GC.Collect
to reclaim memory before loading the next level.
For more details on how to enable and disable garbage collection at runtime, refer to Configuring garbage collection.
GarbageCollector.GCMode
API referenceScripting.GarbageCollector
API referenceDid you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.