When we previously coded our first spell, I said to set the units and triggers to null at the end of the
function, without much explanation. The reason is that not setting these local objects to null will cause a
memory leak. It's a minor one compared to other leak types, but still must be avoided to have correct code.
This is a type of memory leak that we do not need to worry about in GUI, because it only affects local
variables: the local leak.
Previously, we learned about how objects stay in memory while the reference to them is lost, causing a memory leak. But now let's look at the reference to the object itself, ignoring the object in memory.
When we declare a local object variable in a function, the computer will allocate memory for that reference. The function then executes and reaches the end. As you know, local variables only exist in a single function and are created every time the function runs. When the function ends, local object variables are not destroyed, but rather become unreachable. If these object variables still contain a reference to an object (even a destroyed object), the reference itself remains in memory forever and is itself leaked. Here is a function that declares some locals but does not null them:
function onCast takes nothing returns nothing
local unit source = GetTriggerUnit()
local unit target = GetSpellTargetUnit()
Let's look at a memory diagram to see what happens. At the beginning the function is running, this is what it looks like:
The function contains these unit references
Now when the function ends:
Locals are "abandoned" in memory
These are no longer reachable, but still take up space. Setting them to null solves this. If you null your references before the function ends, they won't take up space in memory anymore. This effectively "deletes" your references.
Note that strings (and a few others like Player) do not have to be nulled, because of how they were coded in WC3. But in general, anything that is a "Handle" can leak locally.
- Set your local reference variables to null before the function ends
- If not, they will remain in memory and cause a small leak
Back to lessons