首页 > 其他 > 详细

三、提高反射效率

时间:2020-04-15 18:13:14      阅读:60      评论:0      收藏:0      [点我收藏+]

反射机制对程序的运行在性能上有一定的影响,速度慢

一、 如何提高反射的性能

1) 通过 setAccessible 提高性能

a) setAccessible 启用和禁用访问安全检查的开关,值为 true 则指示反射的对象在使用时应该取消 Java 语言访 问检查,值为 false 则指示反射的对象不实施 Java 语言 访问检查,并不是为 true 就能访问为 false 就不能访问

b) 禁止安全检查,可以提高反射的运行速度

 1 public class Test3 {
 2     public static void test01(){
 3         //User u=new User();
 4         Object obj=new Object();
 5         long startTime=System.currentTimeMillis();
 6         for(int i=0;i<1000000000L;i++){
 7             obj.hashCode();
 8         }
 9         long endTime=System.currentTimeMillis();
10         System.out.println("调用普通方法,执行10亿次:"+(endTime-startTime)+"ms");
11     }
12     public static void test02() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
13         Object obj=new Object();
14         Class c=obj.getClass();
15         //获取指定的方法
16         Method m=c.getDeclaredMethod("hashCode", null);
17         long startTime=System.currentTimeMillis();
18         for(int i=0;i<1000000000L;i++){
19             //执行这个方法
20             m.invoke(obj, null);
21         }
22         long endTime=System.currentTimeMillis();
23         System.out.println("通过反射动态方法调用,执行10亿次:"+(endTime-startTime)+"ms");
24     }
25     public static void test03() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
26         Object obj=new Object();
27         Class c=obj.getClass();
28         //获取指定的方法
29         Method m=c.getDeclaredMethod("hashCode", null);
30 
31         m.setAccessible(true);//不执行安全检查
32 
33         long startTime=System.currentTimeMillis();
34         for(int i=0;i<1000000000L;i++){
35             //执行这个方法
36             m.invoke(obj, null);
37         }
38         long endTime=System.currentTimeMillis();
39         System.out.println("通过反射动态方法调用,不启用安全检查,执行10亿次:"+(endTime-startTime)+"ms");
40     }
41     public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
42         test01();
43         test02();
44         test03();
45     }
46 }

技术分享图片

 

三、提高反射效率

原文:https://www.cnblogs.com/qiaoxin11/p/12706603.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!