当前位置: 技术问答>java相关
请教:该类编译后运行的输出是什么,为什么会有这样的结果???
来源: 互联网 发布时间:2015-01-17
本文导语: public class SizeOfAndStringPool { public static void main(String[] args) throws Exception { long m0, m1, m2, m3, m4, m5; String s1, s2, s3, s4, s5; Runtime rt = Runtime.getRuntime(); rt.gc(); ...
public class SizeOfAndStringPool {
public static void main(String[] args) throws Exception {
long m0, m1, m2, m3, m4, m5;
String s1, s2, s3, s4, s5;
Runtime rt = Runtime.getRuntime();
rt.gc();
m0 = rt.freeMemory();
// Very long string
s1 = "a";
m1 = rt.freeMemory();
s2 = s1; // no new obj created
m2 = rt.freeMemory();
// add an even longer one, 2 new objs created
s3 = s2 + "a";
m3 = rt.freeMemory();
s4 = s3; // no new obj created
m4 = rt.freeMemory();
// Assign the same string of s1 to s5
// since string pooling, no new obj created
s5 = "a";
m5 = rt.freeMemory();
// The results are in the reasonable error range
// since new String obj has mem-overhead too
System.out.println("s1 took " + (m0-m1) + " bytes."); // 2456
System.out.println("s2 took " + (m1-m2) + " bytes."); // 0
System.out.println("s3 took " + (m2-m3) + " bytes."); // 4408
System.out.println("s4 took " + (m3-m4) + " bytes."); // 0
System.out.println("s5 took " + (m4-m5) + " bytes."); // 0
}
}
public static void main(String[] args) throws Exception {
long m0, m1, m2, m3, m4, m5;
String s1, s2, s3, s4, s5;
Runtime rt = Runtime.getRuntime();
rt.gc();
m0 = rt.freeMemory();
// Very long string
s1 = "a";
m1 = rt.freeMemory();
s2 = s1; // no new obj created
m2 = rt.freeMemory();
// add an even longer one, 2 new objs created
s3 = s2 + "a";
m3 = rt.freeMemory();
s4 = s3; // no new obj created
m4 = rt.freeMemory();
// Assign the same string of s1 to s5
// since string pooling, no new obj created
s5 = "a";
m5 = rt.freeMemory();
// The results are in the reasonable error range
// since new String obj has mem-overhead too
System.out.println("s1 took " + (m0-m1) + " bytes."); // 2456
System.out.println("s2 took " + (m1-m2) + " bytes."); // 0
System.out.println("s3 took " + (m2-m3) + " bytes."); // 4408
System.out.println("s4 took " + (m3-m4) + " bytes."); // 0
System.out.println("s5 took " + (m4-m5) + " bytes."); // 0
}
}
|
s1 = "a"; 只是将"a"的句柄付与s1,s2 = s1之类也是一样。
只有s3 = s2 + "a";这样的右值是表达式的才会分配内存给结果。
对象赋值实际上只是句柄的赋值
只有s3 = s2 + "a";这样的右值是表达式的才会分配内存给结果。
对象赋值实际上只是句柄的赋值