package com.base;
public class Sizeof
{
public static void main (String [] args) throws Exception
{
// Warm up all classes/methods we will use
runGC ();
usedMemory ();
// Array to keep strong references to allocated objects
final int count = 100000;
Object [] objects = new Object [count];
long heap1 = 0;
// Allocate count+1 objects, discard the first one
for (int i = -1; i < count; ++ i)
{
Object object = null;
// Instantiate your data here and assign it to object
// object = new Object ();
// object = new Integer (i);
object = new Boolean(true);
//object = new Long (i);
//object = new String ();
//object = new byte [128][1]
if (i >= 0)
objects [i] = object;
else
{
object = null; // Discard the warm up object
runGC ();
heap1 = usedMemory (); // Take a before heap snapshot
}
}
runGC ();
long heap2 = usedMemory (); // Take an after heap snapshot:
final int size = Math.round (((float)(heap2 - heap1))/count);
System.out.println ("'before' heap: " + heap1 +
", 'after' heap: " + heap2);
System.out.println ("heap delta: " + (heap2 - heap1) +
", {" + objects [0].getClass () + "} size = " + size + " bytes");
for (int i = 0; i < count; ++ i) objects [i] = null;
objects = null;
}
private static void runGC () throws Exception
{
// It helps to call Runtime.gc()
// using several method calls:
for (int r = 0; r < 4; ++ r) _runGC ();
}
private static void _runGC () throws Exception
{
long usedMem1 = usedMemory (), usedMem2 = Long.MAX_VALUE;
for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++ i)
{
s_runtime.runFinalization ();
s_runtime.gc ();
Thread.currentThread().yield ();
usedMem2 = usedMem1;
usedMem1 = usedMemory ();
}
}
private static long usedMemory ()
{
return s_runtime.totalMemory ()- s_runtime.freeMemory ();
}
private static final Runtime s_runtime = Runtime.getRuntime ();
} // End of class
[Quote=引用楼主 mfdate 的帖子:]
java中的 boolean 在内存中占多少字节?
[/Quote]
答:我的结论是:
1)boolean a=true;//这个a在JVM中占4个字节即:32位。
2)boolean[] b = new boolean[10];//数组时,每一个boolean在JVM中占一个字节。
理由:
1)JAVA规范中没有定义boolean类型的大小。
2)但是:在JVM规范第2版中讲得十分清楚。我上边的结论就是从它当中取出来的。
根据:(JVM规范第2版 3.3.4节)
Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data type.
Where Java programming language boolean values are mapped by compilers to values of Java virtual machine type int, the compilers must use the same encoding. 而:Java virtual machine type int, whose values are 32-bit signed two's-complement integers。 Arrays of type boolean are accessed and modified using the byte array instructions
In Sun's JDK releases 1.0 and 1.1, and the Java 2 SDK, Standard Edition, v1.2, boolean arrays in the Java programming language are encoded as Java virtual machine byte arrays, using 8 bits per boolean element.