<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(); }