java反射耗时测试案例解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java反射耗时测试案例解析

  2021-04-02 我要评论

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调用的性能差距。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们