支付寶一面:一個 Java 對象到底有多大?被問傻眼了!!
來源:http://blog.lichengwu.cn/
一個Java對象到底有多大?
Java對象結(jié)構(gòu)
-
Object Header -
Class Pointer -
Fields
hash(25)+age(4)+lock(3)=32bit
unused(25+1)+hash(31)+age(4)+lock(3)=64bit
2024最新架構(gòu)課程,對標培訓(xùn)機構(gòu)
/*** The value of the <code>Integer</code>.** @serial*/private final int value;
4(object header)+4(pointer)+4(length)+4*10(10個int大小)=52byte 由于需要8位對齊,所以最終大小為`56byte`。
節(jié)約內(nèi)存原則
1)盡量使用基本類型,而不是包裝類型。
2)斟酌字段類型,在滿足容量前提下,盡量用小字段。
/*** The array buffer into which the elements of the ArrayList are stored.* The capacity of the ArrayList is the length of this array buffer.*/private transient Object[] elementData;/*** The size of the ArrayList (the number of elements it contains).** @serial*/private int size;
3)如果可能,盡量用數(shù)組,少用集合。
數(shù)組中是可以使用基本類型的,但是集合中只能放包裝類型!
4)小技巧
-
時間用long/int表示,不用Date或者String。 -
短字符串如果能窮舉或者轉(zhuǎn)換成ascii表示,可以用long或者int表示。
總結(jié)
評論
圖片
表情
