Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation areas in C++ (Stack vs heap vs Static)

Tags:

c++

linux

x86

I understand there are three, not two areas of memory in C++: stack, heap AND the area for static-assigned features. I have two questions

  1. Why is the heap so much slower than the stack? Surely it should just be one extra level of indirection?

  2. Is the area of memory allocated for static "features" (variables, functions, classes) provide faster performance than the heap?

like image 461
user997112 Avatar asked Jan 05 '13 14:01

user997112


1 Answers

When comparing the speed of stack, heap or static allocation areas, there are two different speeds to compare.

First, there is the speed of access. This is comparable for each of the three areas, although local (stack allocated) variables can have a slight edge because they are easier for the compiler to cache in a CPU register. Otherwise, it is essentially just memory access.

Secondly, there is the speed of allocation. This is where the big differences arise.
Statically allocated objects get their memory reserved at program startup (or library load time when they reside in a dynamically loaded library), so their allocation time is immesurably short as far as the program is concerned.
Stack allocated objects are also cheap to allocate, because they take a predictable allocation pattern (last allocated == first deallocated) that the compiler can easily take into account. For example, if an application has multiple threads, it will also have multiple stacks (each stack reserved for one thread), so the threads don't have to compete with each other for access to the stack memory.
Heap allocated objects are the difficult ones, because the heap is used for everything that does not nicely fit within the earlier groups. Also, there is typically only one heap for the entire application, so thread synchronisation is needed to allocate memory from the heap. And, because the allocation/deallocation patterns are fairly random, measures have to be taken to ensure not too much heap memory gets 'lost' due to fragmentation of the heap. This all takes some time that gets paid when doing an allocation or deallocation.

like image 172
Bart van Ingen Schenau Avatar answered Nov 06 '22 05:11

Bart van Ingen Schenau