2

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"));
1
  • There is a good reason for this warning. You’re querying an implementation detail which is not guaranteed to be there or to behave as you expect. What if a future version chooses between three different optimized encodings? Commented Sep 12, 2018 at 10:47

1 Answer 1

2

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";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I did not know about JOL, interesting to see the overhead of small strings. I'll probably not use it directly but estimate the size based on those values.
@JörnHorstmann right. there are samples in that project that are far more interesting, like inheritance gaps, or a huge gap in .class, etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.