我想计算两个指向相同文本的字符串对象使用的内存。由于两个String都从以下结果指向相同的地址,因此我预计GraphLayout.parseInstance(text1,text2).toFootprint()中使用的总内存应为40(char [])+ 24(String类型)= 64字节。 )。但是,将一个额外的24个String类型的字节添加到此总数中。还是我错过了一些不应以这种方式使用API的东西?
PrintWriter pw = new PrintWriter(out);
String text1 = "1111111111";
String text2 = "1111111111";
pw.println(GraphLayout.parseInstance(text1).toPrintable());
pw.println(GraphLayout.parseInstance(text2).toPrintable());
pw.println(GraphLayout.parseInstance(text1, text2).toPrintable());
pw.println(GraphLayout.parseInstance(text1, text2).toFootprint());
pw.println(RamUsageEstimator.sizeOf(text1));
pw.close();
这是执行结果:
Both text1 and text2 share the same String as they are pointing to the same address.
java.lang.String@4f209819d object externals:
ADDRESS SIZE TYPE PATH VALUE
76c6675e0 24 java.lang.String (object)
76c6675f8 40 [C .value [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
java.lang.String@4f209819d object externals:
ADDRESS SIZE TYPE PATH VALUE
76c6675e0 24 java.lang.String (object)
76c6675f8 40 [C .value [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
The GraphLayout of both text1 and text2 shows there are only one String object.
java.lang.String@4f209819d, java.lang.String@4f209819d object externals:
ADDRESS SIZE TYPE PATH VALUE
76c6675e0 24 java.lang.String <r2> (object)
76c6675f8 40 [C <r1>.value [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
The GraphLayout of both text1 and text2 shows there are only one String object.
java.lang.String@4f209819d, java.lang.String@4f209819d footprint:
COUNT AVG SUM DESCRIPTION
1 40 40 [C
2 24 48 java.lang.String
3 88 (total)