- 如果只有堆棧內存,沒有堆內存,將會創建哪些問題?我認爲它會讓節目非常快。
- 我知道對象是在堆內存中創建的。 但是如果在堆棧內存中創建對象,會有什麼問題?爲什麼我們創建了堆內存?
堆棧
very fast access
don't have to explicitly de-allocate variables
space is managed efficiently by CPU, memory will not become fragmented
limit on stack size (OS-dependent)
堆
variables can be accessed globally
no limit on memory size
(relatively) slower access
no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
you must manage memory (you're in charge of allocating and freeing variables)
variables can be resized using realloc()
堆棧比堆更快訪問的想法充其量只是部分正確。確實,在堆棧上分配空間比分配堆內存要快,但是在內存訪問之後就是內存訪問。確實,接近當前堆棧頂端的東西更有可能處於緩存中,但如果您開始在堆棧中分配大量東西,那麼這種優勢也會消失。 –