Does JavaScript use stack or heap for memory allocation or both?

View original thread
HazNode's photo

The simple answer is: Heap. But it doesn't really matter because:

  1. JS is a dynamic language and as such memory allocation happens dynamically.
  2. JS has loose typing which generally makes it less useful to keep data on the stack. I'm sure the VM uses the stack when it sees fit though.
  3. The stack and heap concept stem from the early days of processors when memory was more or less statically allocated and the stack was typically accessed using a fast 1 opcode instruction as opposed to 3-4 opcodes for a heap or direct memory access. Modern CPU architectures work differently and don't really make a huge difference between stacks and heaps. As long as there is no cache-miss, performance difference should be minor if not negligible. In reality it comes down to how good or bad the the VM is at realtime optimisation and memory management.
Kamil Tomšík's photo

Stack is freed automatically at the end of call unlike heap which has to be garbage collected, which in turn can (and will if we're talking about long-running node.js app) cause "stop-the-world" problem