java反射耗时测试

java反射相对与普通的对象调用原理上来说更加耗时,在调用次数较少的情况下可忽略性能损失,但当调用次数非常多时,需要考虑到此问题,即调用次数过多时不宜使用反射,以下举例:

package com.test.reflection;

import java.lang.reflect.Method;

public class ReflectionDemo {

    public static void main(String[] args) throws Exception {
        // 常规方式
        Student student = new Student();
        long startNormal = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            student.setName("hello");
        }
        System.out.println("timeNormal=" + (System.currentTimeMillis() - startNormal));

        //反射方式
        Class<?> cla=Class.forName("com.test.reflection.Student");
        long startReflection = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            Method method=cla.getDeclaredMethod("setName", String.class);
            method.invoke(cla.newInstance(), "hello");
        }
        System.out.println("timeReflection=" + (System.currentTimeMillis() - startReflection));
    }

    

}

运行结果:

timeNormal=8
timeReflection=537

这是在简单使用反射调用某个方法的场景下1000000调用的性能差距。

猜你喜欢

转载自www.cnblogs.com/silenceshining/p/11689448.html