Java Reflection Performance

前端 未结 14 1604
感动是毒
感动是毒 2020-11-22 08:25

Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?

14条回答
  •  盖世英雄少女心
    2020-11-22 09:15

    Yes, always will be slower create an object by reflection because the JVM cannot optimize the code on compilation time. See the Sun/Java Reflection tutorials for more details.

    See this simple test:

    public class TestSpeed {
        public static void main(String[] args) {
            long startTime = System.nanoTime();
            Object instance = new TestSpeed();
            long endTime = System.nanoTime();
            System.out.println(endTime - startTime + "ns");
    
            startTime = System.nanoTime();
            try {
                Object reflectionInstance = Class.forName("TestSpeed").newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            endTime = System.nanoTime();
            System.out.println(endTime - startTime + "ns");
        }
    }
    

提交回复
热议问题