In this lesson, you will learn how to manually trigger Unreal Engine’s Garbage Collector (GC) to reclaim memory during predictable, non-critical moments in your gameplay.
Why Force a GC Cycle?
Unreal Engine automatically runs garbage collection periodically to clean up UObjects that are no longer referenced. While this is usually efficient, the automatic sweep can sometimes trigger during "hot" moments of gameplay—such as a frantic combat encounter—leading to micro-stutters or frame drops. By manually invoking a collection sweep during "quiet" moments, like while a player is viewing a loading screen, navigating a menu, or transitioning between rooms, you can keep your memory usage lean without interrupting smooth gameplay.
Using CollectGarbage
The engine provides a global function, CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS), which tells the engine to perform a full sweep immediately.
To implement this, you simply call the function in your code. For instance, if you are transitioning levels or clearing out a large set of temporary procedural objects, you might do this:
// Inside a non-critical transition or menu function
void AMyGameMode::PerformCleanup()
{
// Perform a full synchronous garbage collection cycle
CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS);
}
Strategic Timing
The key to optimizing memory is choosing the right moment. If you call CollectGarbage every single frame, your game will grind to a halt because the engine will be constantly scanning memory. Instead, use this tool sparingly. A common pattern is to wait for the player to reach a "safe state" where the CPU is under-utilized, then force the cleanup to ensure the engine has plenty of overhead for the next gameplay segment.
By taking control of the timing, you transform the garbage collector from a background process that might "hitch" your game at the wrong time into a maintenance task that occurs precisely when you have the performance budget to spare.
Key Takeaway: You can use CollectGarbage() to move memory reclamation work into quiet moments of your game’s execution, preventing the engine from triggering expensive GC spikes during critical gameplay.