当前位置: 技术问答>java相关
请问heap和stack有什么区别?
来源: 互联网 发布时间:2015-03-05
本文导语: | Stack. This lives in the general RAM (random-access memory) area, but has direct support from the processor via its stack pointer. The stack pointer is moved down to create new memory and moved up to release that memory. This is an extre...
|
Stack. This lives in the general RAM (random-access memory) area, but has direct support from the processor via its stack pointer. The stack pointer is moved down to create new memory and moved up to release that memory. This is an extremely fast and efficient way to allocate storage, second only to registers. The Java compiler must know, while it is creating the program, the exact size and lifetime of all the data that is stored on the stack, because it must generate the code to move the stack pointer up and down. This constraint places limits on the flexibility of your programs, so while some Java storage exists on the stack ?in particular, object handles ?Java objects are not placed on the stack.
Heap. This is a general-purpose pool of memory (also in the RAM area) where all Java objects live. The nice thing about the heap is that, unlike the stack, the compiler doesn't need to know how much storage it needs to allocate from the heap or how long that storage must stay on the heap. Thus, there's a great deal of flexibility in using storage on the heap. Whenever you need to create an object, you simply write the code to create it using new and the storage is allocated on the heap when that code is executed. And of course there's a price you pay for this flexibility: it takes more time to allocate heap storage.
Heap. This is a general-purpose pool of memory (also in the RAM area) where all Java objects live. The nice thing about the heap is that, unlike the stack, the compiler doesn't need to know how much storage it needs to allocate from the heap or how long that storage must stay on the heap. Thus, there's a great deal of flexibility in using storage on the heap. Whenever you need to create an object, you simply write the code to create it using new and the storage is allocated on the heap when that code is executed. And of course there's a price you pay for this flexibility: it takes more time to allocate heap storage.
|
前者动态,后者静态
|
在C/C++中,数组都是放在stack中的,而动态分配的(如:malloc)是在heap中。
在java中,所有用new创建的对象都是放在heap中的,数组也是对象。
在java中,所有用new创建的对象都是放在heap中的,数组也是对象。