为了账号安全,请及时绑定邮箱和手机立即绑定

堆栈与堆:了解Java内存分配

标签:
MySQL

原文地址: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. 栈在编译的时候分配,堆是在程序运行的时候分配

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Python工程师
手记
粉丝
63
获赞与收藏
531

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消