Jörn Horstmann
Jörn Horstmann

Reputation: 34044

Calculate memory usage of (compact) strings

With java's compact strings feature, is there a public api to get the actual encoding or memory usage of a string? I could call either package private method coder or private method isLatin1 and adjust the calculation, but both will result in an Illegal reflective access warning.

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"));

Upvotes: 2

Views: 224

Answers (1)

Eugene
Eugene

Reputation: 121028

That is pretty easy with JOL (but I am not entirely sure this is what you want):

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

For encoding there isn't a public API, but you can deduce it...

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

Upvotes: 2

Related Questions