As "garbage collection" literally implies, collecting garbage which refers to irrelevant or unnecessary things.
Examine the following code:
name was declared, memory space was created to hold the value "Dillion".
name is just a label to that memory space. Later on,
So what happens to "Dillion"?
It is collected as garbage. This can also be seen as a memory management technique, though not 100% effective. Hence, developers should dearly consider memory management during development and not rely on garbage collection.
There are three processes involved in memory usage.
This refers to assigning space for a value.
From the above, memory spaces are assigned for the number type
variable1 and the object type (which is a collection of values)
This refers to any form of usage of those values. For example:
var result = variable1 + 23;
As seen above,
variable1 which was initialized is now been used.
This is the point where a memory space becomes irrelevant and needs to be collected as garbage.
In lower-level languages, developers would have to explicitly release a memory space but in higher-level languages, this is done automatically in the background with the garbage collection feature.
The general way of doing this is by checking if a value is REFERENCED or in another term, REACHABLE. The garbage collector engine checks to see if a memory space is referenced and if it isn't, it collects it as garbage.
objis declared and assigned an object value. The value is always reachable via the
objvariable, so it is retained.
anotherObjis declared and assigned an object value.
newObjis assigned the reference value of
anotherObj(remember how objects works - mutability).
anotherObjis assigned a new value - 43. But the object value remains. Why? Because we can still access the object (
The garbage collection process (which is done automatically and cannot be controlled) is not a 100% method of memory management. Hence, other methods have to be put in place manually.
There are several other algorithms that the garbage collector engine follows to determine if spaces are irrelevant, but the general thing you should note it tries to verify is "Is the memory space reachable or irrelevant?"
Check out these resources for more details: