Java Reflection: Why is it so slow?

后端 未结 6 1117
独厮守ぢ
独厮守ぢ 2020-11-29 17:30

I\'ve always avoided Java reflection soley based on its reputation for slowness. I reached a point in the design of my current project where being able to use it would make

6条回答
  •  眼角桃花
    2020-11-29 18:26

    It seems that if you make the constructor accessible, it will execute much faster. Now it's only about 10-20 times slower than the other version.

        Constructor c = B.class.getDeclaredConstructor();
        c.setAccessible(true);
        for (int i = 0; i < numTrials; i++) {
            c.newInstance();
        }
    
    Normal instaniation took: 47ms
    Reflecting instantiation took:718ms
    

    And if you use the Server VM, it is able to optimize it more, so that it's only 3-4 times slower. This is quite typical performance. The article that Geo linked is a good read.

    Normal instaniation took: 47ms
    Reflecting instantiation took:140ms
    

    But if you enable scalar replacement with -XX:+DoEscapeAnalysis then the JVM is able to optimize the regular instantiation away (it will be 0-15ms) but the reflective instantiation stays the same.

提交回复
热议问题