Is data allocated on the heap slower for access than data allocated on the stack?

I heard conflicting opinions on this.

Some say that the access to the data allocated on the heap (ie, std::vectoror dynamic arrays allocated through malloc), always slightly slower than access to data allocated on the stack, because the process must always pass through an intermediate pointer to access the data probably located on a completely different area of ​​memory; on the other hand, they support, access to the data allocated on the stack does not require passing through this intermediate pointer, and this data is most likely already cached.

Others argue that only the data distribution is slower in a heap than stack (due to overhead malloc, mmapand similar functions), but access is not, except in rare cases where the stack and heap is located on different physical disks.

What is the truth?

+4
source share
2 answers

The truth (at least on most modern processors) is that both stacks and heaps do the same thing, since they are both just pieces of RAM. Thus, dereferencing a pointer is almost the same.

, /, malloc free syscalls . malloc . , , (, push, pop). - ( ) .

, , ( , ) . , , , , swap .

, , , , . , . , , cpu.

, std::vector . , , - , , . , . , .

, . ( ). . . . (, , , ). . , .

+2

, , (.. std::vector , malloc), , , , , , , ; , , , , , , , .

. . - (SP) , (, BP, AP).

, - . , , , .

, , (- malloc, mmap ),

. .

0

Source: https://habr.com/ru/post/1689821/


All Articles