Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A (very) quick introduction to garbage collection
// When you create a new object
var obj = {data: "some data here"};
/* The JavaScript runtime environment allocates memory for you.
__________________________
Your computer's memory ----> || Location || Value ||
||------------------------||
It has to store that obj is || 0 || 2424 ||
an object, that it has a || 1 || 1002 ||
property named data, and || 2 || 327871 ||
data is the string || 3 || 0 ||
"some data here" || ... || ... ||
--------------------------
*/
obj = null; // What happens when there's no way to access this object again?
/* If the JavaScript runtime did nothing, all your memory would eventually be used to store
data you don't need any more.
Garbage collection is the process of cleaning up data like this that's no longer useful.
The simplest way to do this is to store a flag on every memory location:
_________________________________________
Your computer's memory ----> || Location || Value || Still used? ||
||------------------------||--------------||
|| 0 || 2424 || yes ||
|| 1 || 1002 || yes ||
|| 2 || 327871 || no ||
|| 3 || 0 || yes ||
|| ... || ... || ... ||
------------------------------------------
Here's one simple algorithm for garbage collection:
1. Mark all memory as not used.
2. Take everything in the current scope and mark it as used.
3. Recursively mark anything referenced by those objects as used.
4. Go through all memory and reclaim anything that's marked as not used.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.