java 基本數(shù)據(jù)類(lèi)型各種情況下在內(nèi)存中存儲(chǔ)位置?
問(wèn)題描述
問(wèn)題:如何理解《Java編程思想-第四版》P23 中,這個(gè)變量直接存儲(chǔ)“值”,并置于堆棧中,因此更加高效一句中的 “堆棧” 兩字,到底是堆還是棧?情況如下:
class demo { private int var1; // 字段1 private Integer var2; // 字段2 public static void main(String[] args) {int var3 = 0; // 變量1demo obj1 = new demo(); // 實(shí)例1 }}我的理解
參考《Java編程思想-第四版》P23 和 《深入理解Java虛擬機(jī):JVM高級(jí)特性與最佳實(shí)踐 第2版》P39-P43,對(duì)于該 demo
實(shí)例1:存儲(chǔ)在堆內(nèi)存中
變量1:存儲(chǔ)在方法棧中
實(shí)例1中的字段1:存儲(chǔ)在堆中
實(shí)例1中的字段2:存儲(chǔ)在堆中
如果是存儲(chǔ)在堆中的話,何來(lái)高效一說(shuō)?
問(wèn)題解答
回答1:我們不能一概而論的說(shuō),基本類(lèi)型數(shù)據(jù)都是放在棧中的!當(dāng)某個(gè) 類(lèi)實(shí)例 中具有基本類(lèi)型時(shí),基本類(lèi)型就放在堆中!
回答2:內(nèi)存分為堆和棧,這你已經(jīng)知道了。
堆內(nèi)存是屬于JVM的,棧內(nèi)存是屬于方法的,方法結(jié)束了,棧內(nèi)存也就沒(méi)了。
程序運(yùn)行main函數(shù)時(shí),有一個(gè)堆內(nèi)存,一個(gè)main的棧內(nèi)存
int var3 = 0;這個(gè)var3,是放在main函數(shù)的棧內(nèi)存中的,是一個(gè)值。
之后demo obj1 = new demo();main函數(shù)的棧內(nèi)存中有了一個(gè)引用變量,obj1,指向了堆內(nèi)存中new出來(lái)的這個(gè)實(shí)例。
我們?cè)倏炊褍?nèi)存中的這個(gè)實(shí)例,他有2個(gè)字段,他們都是存放在堆中的。
等到main函數(shù)運(yùn)行結(jié)束時(shí),假如還有別的線程在運(yùn)行,JVM還沒(méi)有結(jié)束,此時(shí),main函數(shù)的棧內(nèi)存被清除,var3,不在了,obj1這個(gè)引用變量也不在了,但是堆內(nèi)存中的那個(gè)實(shí)例依然在,如果沒(méi)有別的引用變量 指向它 ,那么它將在稍后被清除。
回答3:是翻譯錯(cuò)誤,原文中用的是stack,即棧,而不是堆棧。以下是原文:
Special case: primitive typesOne group of types, which you’ll use quite often in your programming, gets special treatment. You can think of these as “primitive” types. The reason for the special treatment is that to create an object with new—especially a small, simple variable—isn’t very efficient, because new places objects on the heap. For these types Java falls back on the approach taken by C and C++. That is, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value directly, and it’s placed on the stack, so it’s much more efficient.
回答4:p22,堆棧指的是stack,堆指的是heap
相關(guān)文章:
1. node.js - mongoDB使用$gte的問(wèn)題2. android - 像支付寶到位這種點(diǎn)擊marker點(diǎn)擊變大怎么做的3. angular.js - ngview配置路由失敗4. html5 - H5頁(yè)面喚起APP導(dǎo)航5. 黑客 - Python模塊安全權(quán)限6. android 微信是如何實(shí)現(xiàn)即時(shí)更新好友頭像的7. javascript - 關(guān)于vuejs讀取數(shù)據(jù)的問(wèn)題8. docker - 如何修改運(yùn)行中容器的配置9. android - 優(yōu)酷的安卓及蘋(píng)果app還在使用flash技術(shù)嗎?10. html5 - bootstrap修改樣式的問(wèn)題
