Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes a heap-based Scheme slower than a stack-based Scheme?

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?

like image 755
Patrick Li Avatar asked Jan 18 '12 18:01

Patrick Li


People also ask

Why is the heap slower than the stack?

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.

Why is the stack faster than the heap?

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.

Which is faster stack allocation or heap allocation?

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.

What is the difference between the stack and the heap?

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.


1 Answers

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.

like image 77
John Clements Avatar answered Jan 03 '23 14:01

John Clements