Heap vs Stack in regard to read/write speed

2019-07-19 01:36发布

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?

3条回答
乱世女痞
2楼-- · 2019-07-19 02:12

No at all. heap ad stack are areas in the virtual address space that the operating system gives t your app. Their difference is what your app stores in the stack and what in the heap. All the reference types are stored in the heap and all the value types are stored in stack. Furthermore the lifetime of the things that are stored in the stack has the same duration as the lifetime of your app, while types stored in the heap may be garbage collected and the memory that they were using be reclaimed.

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-19 02:17

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-07-19 02:31

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 than malloc).

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.

查看更多
登录 后发表回答