I am developing a compiler for a language similar to Scheme, and am reading through Dybvig's thesis. In it, he says that achieved most of his performance gain by allocating call frames on the stack instead of on the heap. There's several tricks that need to be done in order to actually make this work in the presence of closures and continuations.
My question is where does this performance gain come from? Is it purely because we put less strain on the garbage collector?
Put another way: Assuming we have an infinite amount of memory, would stack allocated call frames still be faster than heap allocated call frames?
Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly. Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.
The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free.
Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread. Memory allocation and de-allocation is faster as compared to Heap-memory allocation. Stack-memory has less storage space as compared to Heap-memory.
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.
I think Eli answered your question, so I'm going to paste his comment here and get credit for it :).
Eli Barzilay writes:
(a) dealing with the heap takes more time since it requires scanning it (it's not linear like the stack); (b) practically all cpu architectures put extra emphasis on making stack access as fast as possible, and not so with the heap.
To this I would add general hand-waving about cache locality. That is, a stack keeps all the action in a very small part of memory, which will almost definitely stay in the cache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With