Jul 23, 2019

[java] type instance initialization constructor does not do inline.

Reference:
https://pangin.pro/posts/computation-in-static-initializer
https://cl4es.github.io/2019/02/21/Cljinit-Woes.html


HotSpot does not inline methods of uninitialized classes.
source code:
https://hg.openjdk.java.net/jdk-updates/jdk11u/file/cd1c042181e9/src/hotspot/share/opto/bytecodeInfo.cpp#l455

Access to a static field from a static method of uninitialized class may be an overwhelming obstacle for HotSpot compiler.

Work around:
Just don't do heavy computation in an uninitialized class directly. :-\
(From compiled language point of view, it's quite absurd and duh~duh~duh~)

If putting the computation logic in a helper class with no static initializer, it won’t suffer from performance penalty.

e.g
public class StaticExample {
    static final long[] TABLE = Helper.prepareTable();

    private static class Helper {

        static long[] prepareTable() {
            long[] table = new long[100_000_000];
            for (int i = 1; i < table.length; i++) {
                table[i] = nextValue(table[i - 1]);
            }
            return table;
        }

        static long nextValue(long seed) {
            return seed * 0x123456789L + 11;
        }
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.