Why stack is faster than heap and what exactly is stack?

Shared resources are slower than private resources because of the overhead of managing the sharing.

The stack area of memory is private to the procedure, the heap is shared by all procedures (currently executing or not).

In addition, there is the lifetime issue: the stack area is recycled at the time of completion of the procedure. Some other procedure will use it. Only one procedure is executing at one time (ignore multithreading for now). Stack use ties lifetime of variables to lifetime of procedures, a nice abstraction. But some Fortran variables are meant to survive completion of procedures (they have the SAVE attribute), so they cannot be put on the stack.

It’s called a stack because we always recycle the last thing we ordered (it shadows procedure entry and termination). On the heap, recycling is not predictable: any item could be the next to be recycled. This creates “holes”, leading to inefficiency: some memory requests cannot be satisfied because no hole is big enough (even though the total hole space is more than enough). The stack doesn’t have holes but it can run out quicker because it is generally provisioned smaller than the heap by the operating system.

[Added] There’s no error handling when using the stack. If it runs out, there’s no recovery and your program will crash if you’re lucky (and will initiate WW3 if you are not). There is error handling when using the heap so you can take action (ALLOCATE will fail with a STAT= specifier being set).

6 Likes