Today I Learned - Rocky Kev

TIL the stack and heap

POSTED ON:

TAGS:

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:

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:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.