See all glossary termsReference counting is a memory management technique that automatically frees data from the computer's Random Access Memory (RAM) when it is no longer needed.
Reference counting works by tracking how many references exist to a piece of data: in Godot, that's how many variables or objects point to a resource or object in memory. When the reference count reaches zero, no one is using the data anymore, and it can be safely erased.
Reference counting is a simple and efficient way to manage memory for scripting real-time applications like games. It tracks memory usage reliably, offering a balance between stable performance and ease of use.
Godot uses reference counting to manage resources and nodes in the scene tree.
When you create a new object or resource in Godot and either assign it to a variable, to a node, or add it to the scene tree, the engine increases its reference count to 1. When you assign the object to another variable, the reference count increases again.
When a variable is set to null,
the reference count decreases by 1. Godot forgets about the object or resource when the reference count reaches zero.
We usually explicitly remove nodes by calling Node.queue_free()
, which removes the node and all its children from the scene tree.
Finally, because the engine tracks everything, everything gets cleaned up when the game or the editor is closed.
Isn't this reference counting inefficient?When the computer allocates memory to your program or when you ask it to erase data, it doesn't happen instantly. The operating system and the computer's hardware have to run many operations to allocate or de-allocate memory, which can greatly impact performance.Under the hood, Godot doesn't free memory the moment the reference count reaches zero. Instead, it uses a growth-only memory allocation strategy for performance. When you stop using nodes and resources in your game, the engine doesn't return the memory to the operating system. Instead, it keeps the memory allocated and available to replace the unused data with new data as your game needs it.As you unload data, for example, when changing the game level, the engine keeps all the memory allocated and replaces the old level's data with the new one. It also preserves all the resources it can between the levels to avoid reloading them.To learn more about memory management in the engine core, see this video presentation by the engine's tech lead: Memory management in Godot. school.gdquest.com - 0.3.5-2024-12-12T18:17:18.104Z-a38dc74be3238fd1ea161f4df67b95520741da9d-release