I just went through a bunch of stack vs heap threads here on Stack Overflow (and other random sites found through Google), and yet I can't find an answer that provides much (if any) depth to the issue of read/write speed (most answers and articles focus on allocation speed).
If I'm writing a C program (in my case, a game) where I'm storing object data in a buffer that's a few kilobytes in size, will it make a difference (in terms of access speed) if that buffer is allocated on the stack or on the heap? Or will the compiler treat a buffer of that size the same either way when it comes to deciding where on the hardware (i.e. cache or RAM) to store it?
No at all.
heap
adstack
are areas in the virtual address space that the operating system gives t your app. Their difference is what your app stores in thestack
and what in theheap
. All the reference types are stored in theheap
and all the value types are stored instack
. Furthermore the lifetime of the things that are stored in thestack
has the same duration as the lifetime of your app, while types stored in theheap
may be garbage collected and the memory that they were using be reclaimed.There is no difference in the access speed, its the same memory after all. Compiler never decide where buffer should be stored physically. It is hardware and operating system business.
On a typical modern CPU and OS, no, I wouldn't expect any difference in average access time, likelihood of cache miss, or (much worse) likelihood of page fault based on whether the buffer is in heap or stack. The only thing that should matter is your pattern of access to it, compared to other use of memory. However, there may be embedded or special-purpose platforms where the stack is kept in a different kind of memory than the heap.
You're ignoring a third possibility, non-heap memory (allocated by some OS-specific call, such as
mmap
, rather thanmalloc
).Finally, if you want to completely remove the possibility of page faults, the OS may provide a way to do that; for example,
mlock
on POSIX.