java反射耗时测试案例解析

网友投稿 215 2022-12-25


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 =zTuJmvxsF 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("timeReflzTuJmvxsFection=" + (System.currentTimeMillis() - startReflection));

}

}

运行结果:

timeNormal=8

timeReflection=537

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring boot过滤器FilterRegistrationBean实现方式
下一篇:IntelliJ IDEA 安装教程2019.09.23(最新版)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~