Thanks for the Memory, JavaScript
Let’s talk about memories.
You’ve done a lot of things, and you can remember doing them — remember when you called your teacher ‘Mom’ in elementary school? But you don’t remember everything. That’s because there are limits to your brainpower, and if you tried to remember every little factoid from 7th grade chemistry, you’d prevent yourself from learning anything new. It’s best to periodically clear out the memories you’re not using, so you can perform better day to day.
Your computer program follows a similar principle. Everything you create takes up memory. Some of those things remain useful, and others just sit there taking up space.
Luckily, JavaScript has a handy tool to assess what’s taking up space, and remove anything that’s not needed. That way, your program, like your brain, can remain lean and efficient, maximizing performance. The tool is called garbage collector.
The Memory Life Cycle
A programmer constantly creates new things — objects, variables, functions etc… This ‘creating new things’ is actually assigning new space in memory — the definition of an ‘object’ in computer science is “a location in memory having a value,” and a ‘variable’ is “a storage location paired with an associated symbolic name.”
In JavaScript, these memory-value pairs have a distinct lifecycle.
- Assignment: we assign a space in memory a name and a value. Here’s a JavaScript object stored to a variable: var stuff= {living: “thing”}.
- Execution: We use the ‘stuff’ object for whatever purpose suits our needs. I could console.log(`I am a ${Object.keys(stuff)[0]} ${stuff.living}`) to output “I am a living thing.”
- Release/disposal: once the object isn’t needed anymore, it’s disposed of and the memory space frees up.
We’re very familiar with creating and executing, but what about that third step?
In lower level languages, programmers manually go through and select which objects should be deleted. Sounds awful. In JavaScript, we’re lucky enough to have this task done for us.
Garbage Collector
There’s a computer science term for things that have outlived their usefulness and will no longer be needed: garbage. Specifically, garbage refers to “objects, data, or other regions of the memory… which will not be used in any future computation by the system.”
JavaScript automatically identifies this ‘garbage’ using software called ‘garbage collector.’ Garbage collector’s job is to identify parts of our program that aren’t going to be used anymore, and then dispose of them.
But wait a minute. How does this garbage collector character know what’s garbage? After all, we hand-crafted all the things being tossed on the garbage heap (well, actually, they’re being taken off the heap, since heap is a term that refers to the available memory, but that’s a conversation for another day).
One Man’s Treasure
The key to identifying garbage in your program is referencing.
Much of a program is a complex web of things referencing each other —variables reference objects, and objects in turn reference other objects or variables through their properties.
Earlier, I wrote var stuff= {living: “thing”}, which created a variable called stuff, and set it equal to the object {living: “thing”}. In doing so, I referenced that object.
To garbage collector, that reference is an important sign. Remember, garbage is defined as things “which will not be used in any future computation.” Well, if I’m referencing the object {living: “thing”}, I probably want to use it in a future computation.
But let’s say I reassign the variable stuff… var stuff = {new: “content}. Well, now our old object {living: “thing”} still exists, but our variable ‘stuff’ isn’t pointing to it. In fact, nobody’s pointing to it. It’s just hanging out there, taking up space.
At this point, it’s caught the garbage collector’s notice, and its days are numbered. In the morbid lexicon of memory management, our {living: “thing”} will soon be condemned to death, but more on that in a bit.
Mark and Sweep
Garbage collector works by identifying parts of your program that haven’t been referenced by anything else. Then it kills them to free up space.
To get a bit more technical, there’s something called the Mark-and-sweep algorithm, which moves down a hierarchical chain of everything in your program, from the global object on down. It identifies everything that’s taking up space by following references from object to object, variable to variable. That way, only referenced material is identified.
Everything that’s not identified is chucked. Only material that is being set aside for possible future computation remains. Notable members of the ‘chuck’ pile include crucial parts of our programs like functions that are executed at once. They serve their purpose, but they don’t have to stick around after the fact.
The Morbid World of Memory Management
Things can get a lot more technical from here, but they also get surprisingly morbid. For some reason, the terms relating to memory management and garbage collector are pretty disturbing.
First, there’s the garbage collector, who the oft-cited Memory Management Reference glossary says goes around ‘condemning’ objects to death: “At the start of a collection cycle, the collector may choose to condemn some objects (the condemned set or threatened set) but not to condemn others… The garbage collector will typically divide the set of all objects into generations, and condemn all the objects in a generation together.”
In condemning, it turns out that newly written code is more likely to be chucked than older code. Or, in their words: “Infant mortality… is the observation that, in most cases, young objects are much more likely to die than old objects.”
There’s the whole undead thing… “An undead object is an object that cannot be proven to be dead by the garbage collector, but whose liveness is dubious.”
And “Copying garbage collectors move reachable objects into another semi-space. They leave a forwarding pointer in the old location, pointing to the new. The object at the old location is known as a broken heart.”
What?? I have no idea why the computer scientists who came up with these terms were so sad, but I will never think of memory management the same way again. In any case, you can read more about this stuff in articles like Infant mortality and generational garbage collection (yikes).
Memory Leaks and Google Chrome
When memory isn’t correctly disposed of, our program can get clogged up. That is known as a memory leak, and it can slow performance. Traditionally, browsers have struggled with controlling memory leaks when a user leaves a page open for an extended period of time. To accommodate this issue, Google Chrome has cleverly outfitted its garbage controller to move through a program when a page is inactive, allowing clutter to be cleaned in between page events. So if you took an extra moment to meditate on any of these sentences, your garbage collector may have been hard at work.