计算(紧凑)字符串的内存使用情况

Calculate memory usage of (compact) strings

使用java的压缩字符串功能,是否有public api来获取字符串的实际编码或内存使用情况?我可以调用包私有方法 coder 或私有方法 isLatin1 并调整计算,但两者都会导致 Illegal reflective access 警告。

Method isLatin1 = String.class.getDeclaredMethod("isLatin1");
isLatin1.setAccessible(true);
System.out.println((boolean)isLatin1.invoke("Jörn"));
System.out.println((boolean)isLatin1.invoke("foobar"));
System.out.println((boolean)isLatin1.invoke("\u03b1"));

使用 JOL 这很容易(但我不完全确定这是你想要的):

String left = "Jörn"; 
System.out.println(GraphLayout.parseInstance(left).totalSize()); // 48 bytes

String right = "foobar";
System.out.println(GraphLayout.parseInstance(right).totalSize()); // 48 bytes

String oneMore = "\u03b1";
System.out.println(GraphLayout.parseInstance(oneMore).totalSize()); // 48 bytes

对于编码没有 public API,但你可以推导出它...

private static String encoding(String s) {
    char[] arr = s.toCharArray();
    for (char c : arr) {
        if (c >>> 8 != 0) {
            return "UTF16";
        }
    }
    return "Latin1";
}