原文地址:https://dzone.com/articles/stack-vs-heap-understanding-java-memory-allocation


Similarities and Differences Between Stack and Heap

Both are ways that Java allocates memory and both are stored in the RAM. However, to make things easier to remember, heap is used for dynamic memory allocation, while stack is for static allocations.


** Where is it stored? **Variables that are allocated on the stack are accessible directly from memory, and as such, these can run very fast. Accessing objects on the heap, on the other hand, takes more time.


**When does the allocation happen? **On the stack, memory allocation happens when the program is compiled. Meanwhile, on the heap, it begins when the program is run.


And since this is the case, you would need to know just how much data and memory you are going to need before compiling if you want to use the stack. Another limitation that the stack has is that it cannot handle big chunks of variables that need a lot of memory. If you do not know how much data you are going to need at run time or if you need memory for a lot of data, then you need to use heap.


总结:

  1. 堆和栈都在RAM中,堆用于动态内存分配,而栈用于静态分配。
  2. 栈上分配的变量可以直接从内存访问,因此,这些变量可以非常快速地运行。另一方面,访问堆上的对象需要更多时间。
  3. 栈在编译的时候分配,堆是在程序运行的时候分配