Java Reflection Performance

前端 未结 14 1605
感动是毒
感动是毒 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:11

    You may find that A a = new A() is being optimised out by the JVM. If you put the objects into an array, they don't perform so well. ;) The following prints...

    new A(), 141 ns
    A.class.newInstance(), 266 ns
    new A(), 103 ns
    A.class.newInstance(), 261 ns
    
    public class Run {
        private static final int RUNS = 3000000;
    
        public static class A {
        }
    
        public static void main(String[] args) throws Exception {
            doRegular();
            doReflection();
            doRegular();
            doReflection();
        }
    
        public static void doRegular() throws Exception {
            A[] as = new A[RUNS];
            long start = System.nanoTime();
            for (int i = 0; i < RUNS; i++) {
                as[i] = new A();
            }
            System.out.printf("new A(), %,d ns%n", (System.nanoTime() - start)/RUNS);
        }
    
        public static void doReflection() throws Exception {
            A[] as = new A[RUNS];
            long start = System.nanoTime();
            for (int i = 0; i < RUNS; i++) {
                as[i] = A.class.newInstance();
            }
            System.out.printf("A.class.newInstance(), %,d ns%n", (System.nanoTime() - start)/RUNS);
        }
    }
    

    This suggest the difference is about 150 ns on my machine.

提交回复
热议问题