sizeof,java
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
java sizeof是什麼?讓我們一起來了解一下吧!
java sizeof是一個特殊的概念。在C/C++中,當我們想知道一個對象或者一個原始數據類型所佔用的內存大小時,只需簡單調用sizeof操作符即可,但是,在java中是沒有相應的操作符或者方法來直接完成相應功能的。sizeof 在C/C++得到大量的運用,是程序員必不可少的工具之一。
sizeof在C語言中是一個判斷數據類型長度符號的關鍵詞,它的功能是返回一個對象或者類型所佔的內存字節數。而java的內存管理都有虛擬機負責。所以java要模擬c中對sizeof的實現。
我們首先需要了解Java具有哪些基本數據類型:
1.int 32bit
2.short 16bit
3.long 64bit
4.byte 8bit
5.char 16bit
6.float 32bit
7.double 64bit
8.boolean 1bit
Java基本數據類型封裝類:
1.Integer // 4 byte
2.Short // 2 byte
3.Long // 8 byte
4.Byte // 1 byte
5.Character: // 2 byte
6.Float // 4 byte
7.Double // 8 byte
檢測類型代碼如下:
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 }
檢測代碼如下:
private static void calSize2() { runGC(); long heap1 = 0; final int count = 100000; Object[] objs = new Object[count]; for(int i=-1; i<count; i++) { 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 if(i<0){ obj = null; runGC(); heap1 = usedMemory(); // before memory size } else { objs[i] = obj; } } runGC(); long heap2 = usedMemory(); // after memory size final int size = (int)Math.round( (heap2 - heap1)/(double)count ); System.out.println("heap1 = " + heap1 + "; heap2 = " + heap2); System.out.println("heap2-heap1 = " + (heap2 - heap1) + "; " + objs[0].getClass().getSimpleName() + " size = " + size); for(int i=0; i<count; i++) { objs[i] = null; } objs = null; runGC(); } private static void runGC() { for(int i=0; i<4; i++) { long usedMem1 = usedMemory(); long usedMem2 = Long.MAX_VALUE; for(int j=0; (usedMem1<usedMem2) && (j<500); j++) { rTime.runFinalization(); rTime.gc(); Thread.yield(); usedMem2 = usedMem1; usedMem1 = usedMemory(); } } } private static long usedMemory() { return rTime.totalMemory() - rTime.freeMemory(); }