Java 基本資料型別 sizeof 功能
阿新 • • 發佈:2018-11-07
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
Java基本資料型別int 32bit
short 16bit
long 64bit
byte 8bit
float 32bit
double 64bit
boolean 1bit,This data type represents one bit of information, but its "size" isn't something that's precisely defined.(ref)
Java基本資料型別大小
private static void calSize() { System.out.println("Integer: " + Integer.SIZE/8); // 4 System.out.println("Short: " + Short.SIZE/8); // 2 System.out.println("Long: " + Long.SIZE/8); // 8 System.out.println("Byte: " + Byte.SIZE/8); // 1 System.out.println("Character: " + Character.SIZE/8); // 2 System.out.println("Float: " + Float.SIZE/8); // 4 System.out.println("Double: " + Double.SIZE/8); // 8// System.out.println("Boolean: " + Boolean); }
Java中模擬c中對sizeof的實現 思路: 利用java中GC記憶體回收前後的heap size差別,得出每個object的大小
這是一個程式,java中沒有現成的sizeof的實現,原因主要是java中的基本資料型別的大小都是固定的,所以看上去沒有必要用sizeof這個關鍵字。 實現的想法是這樣的:java.lang.Runtime類中有一些簡單的能涉及到記憶體管理的函式: Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
原始碼:
注意:Object[] objects = new Object[count]; 只是分配了陣列空間,沒有分配物件的空間。陣列中只有引用而已。 結論:下程式碼測試基本物件時,得出的結果象下面: Object obj = null; obj = new Object(); // 8 obj = new Integer( i ); // 16 obj = new Short( (short)i ); // 16 obj = new Long( i ); // 16 obj = new Byte( (byte)0 ); // 16 obj = new Character( (char)i ); // 16 obj = new Float( i ); // 16 obj = new Double( i ); // 16 obj = new Boolean( true ); // 16 obj = new String(); // 40 怎麼會這樣呢???解釋如下: 這個例子寫的很好,正好說明了java中基本型別封裝物件所佔記憶體的大小. 1.簡單的Object物件要佔用8個位元組的記憶體空間,因為每個例項都至少必須包含一些最基本操作,比如:wait()/notify(),equals(), hashCode()等 2.使用Integer物件佔用了16個位元組,而int佔用4個位元組,說了封裝了之後記憶體消耗大了4倍 3.那麼Long看起來比Integer物件應該使用更多空間,結果Long所佔的空間也是16個位元組. 那麼就正好說明了JVM的對於基本型別封裝物件的記憶體分配的規則是如下: Object所佔記憶體(8個位元組)+最大基本型別(long)所佔記憶體(8個位元組) = 16位元組. JVM強制使用8個位元組作為邊界. 所以 所有基本型別封裝物件所佔記憶體的大小都是16位元組. 但是還是有區別,比如: Integer物件雖然佔用了16個位元組的記憶體,但是隻是利用了 Object所佔記憶體(8個位元組)+int所佔記憶體(4個位元組) = 12位元組. 還有4個位元組根本沒有被使用.呵呵,仔細分析了一晚,還是有很多收穫的 測試原始碼下載 參考推薦: 關於java中boolean佔用位元組的問題 java中的 boolean 在記憶體中佔多少位元組? Primitive Data Types (SUN 官方文件) |