TIL the stack and heap
POSTED ON:
TAGS: javascript memory global
We now know that for everything we define in JavaScript, the engine allocates memory and frees it up once we don't need it anymore.
Javascript stores memory in the stack
and the heap
The stack
is a data structure that JavaScript uses to store static data.
const male = true;
const name = 'dave';
const age = 1000
Detail:
- Primitive values and references
- Size is known at compile time
- Allocates a fixed amount of memory
The Heap
is Dynamic memory allocation, storing objects and functions.
Unlike the stack, the engine doesn't allocate a fixed amount of memory for these objects. Instead, more space will be allocated as needed.
function findCats(object) {
// ...
}
Detail:
- Objects and functions
- Size is known at run time
- No limit per object
What about memory leak #
Storing data in global variables is probably the most common type of memory leak.
In non-strict mode:
// In the browser, for instance, if you use var instead of const or let—or leave out the keyword altogether—the engine will attach the variable to the window object.
user = getUser();
var secondUser = getUser();
// The same will happen to functions that are defined with the function keyword.
function getUser() {
return 'user';
}
The garbage collector doesn't know if needs to remove things from global.
To clear it, you assign null.
window.users = null;
via JavaScript's Memory Management Explained
Related TILs
Tagged: javascript