java反射耗时测试案例解析
时间:2021-03-20 10:03:26|栏目: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调用的性能差距。
栏 目:JAVA代码
下一篇:浅谈springmvc的DispatcherServlet分析
本文标题:java反射耗时测试案例解析
本文地址:http://www.codeinn.net/misctech/84753.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




