测试JAVA对象占用的内存方法

依赖JAR包:SizeOf.jar

http://sourceforge.net/projects/sizeof

java.SizeOf is a simple java agent what can be used to calculate the memory size
of java objects.

VM 运行参数 :-javaagent:G:\SizeOf.jar

start the jvm with the argument: -javaagent:<path to>/SizeOf.jar

public class HeapSize {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HashMap<Object, Object> map = new HashMap<Object, Object>();
//		SizeOf.turnOnDebug();
		String a = "a";
		System.out.println("a:" + SizeOf.humanReadable(SizeOf.deepSizeOf(a)));
		String size = SizeOf.humanReadable(SizeOf.deepSizeOf(map));
		System.out.println("map size: " + size);
		ArrayList<Object> list = new ArrayList<Object>();
		size = SizeOf.humanReadable(SizeOf.deepSizeOf(list));
		System.out.println("list size: " + size);
		HashSet<Object> set = new HashSet<Object>();
		size = SizeOf.humanReadable(SizeOf.deepSizeOf(set));
		System.out.println("set size: " + size);
	}

}

输出:

JAVAGENT: call premain instrumentation for class SizeOf
a:88.0b
map size: 128.0b
list size: 80.0b
set size: 160.0b


你可能感兴趣的:(测试JAVA对象占用的内存方法)