To optimize your backend, you must understand the environment your code lives in. Memory is the most precious resource.
1The Stack: Order and Speed
The Stack is a LIFO (Last-In, First-Out) structure. It's used for function calls and small primitive variables (numbers, booleans). It's extremely fast because the memory is allocated and deallocated automatically as functions return.
2The Heap: Flexibility
The Heap is much larger than the Stack but slower to access. It's used for objects, arrays, and functions. Because their size isn't known at compile time, V8 allocates space for them dynamically and tracks them via references on the Stack.
3Mark-and-Sweep
GC works in cycles. It 'marks' every object it can reach starting from the global object. Anything not marked is considered 'garbage' and is 'swept' (deleted) in the next phase. This prevents memory from filling up with dead data.
