Chapter 01 · Who cleans up?01 / 23

Every object needs memory

Every time your program creates an object, a list or a string, the runtime carves a piece out of a region of memory called the heap. Here a web server handles a request: it builds a request object, a user and a cart. Watch the heap fill up, block by block.

The variables that point at those objects live on the stack, inside the function's frame. When handleRequest() returns, the frame is popped and the variables disappear on their own.

The objects don't. They stay in the heap, taking up space nobody can use anymore. Handle a few more requests and the heap is full.

Real heaps hold gigabytes, not 24 blocks of 16 bytes. The shape of the problem is the same.

server.jsin the real world
function handleRequest(req) {
const user = { id: 42, name: 'Alice' }; // allocated on the heap
const cart = { items: [] };
cart.items.push(req.item);
return render(user, cart);
} // user and cart leave the stack. The objects stay.