现在开源框架,为了减少代码耦合度,一般用反射的方法来实现对类方法的查找等。但反射的效率究竟比直接取数据有多大差别。今天,做了个小实验。还请各位高手多多指教。直接来代码:

基本类:

 
  
  1. package test; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5.  
  6. public class A { 
  7.     private int a ; 
  8.     private String b; 
  9.     private List c; 
  10.     public A(){ 
  11.         this.a = 10
  12.         this.b = "abcde"
  13.         c = new ArrayList(); 
  14.         c.add("aaa"); 
  15.         c.add("bbb"); 
  16.     } 
  17.     public int getA() { 
  18.         return a++; 
  19.     } 
  20.     public void setA(int a) { 
  21.         this.a = a; 
  22.     } 
  23.     public String getB() { 
  24.         return b; 
  25.     } 
  26.     public void setB(String b) { 
  27.         this.b = b; 
  28.     } 
  29.     public List getC() { 
  30.         return c; 
  31.     } 
  32.     public void setC(List c) { 
  33.         this.c = c; 
  34.     } 
  35.      

测试类:(引入beanUtil类)
 

 
  
  1. package test; 
  2.  
  3. import java.lang.reflect.InvocationTargetException; 
  4.  
  5. import org.apache.commons.beanutils.BeanUtils; 
  6.  
  7. public class testReflect { 
  8.     public static void main(String[] args){ 
  9.         testReflect tr = new testReflect(); 
  10.         tr.CommonTest(); 
  11.         tr.ReflectTest(); 
  12.     } 
  13.     public static void CommonTest(){ 
  14.         A a = new A(); 
  15.         long timeBegin = System.nanoTime(); 
  16.         for(int i =0 ;i<100000;i++){ 
  17.             a.getA(); 
  18.         } 
  19.         long timeEnd = System.nanoTime(); 
  20.         System.out.println((timeEnd - timeBegin)/1000 
  21.         ); 
  22.     } 
  23.     public static void ReflectTest(){ 
  24.         try { 
  25.             long timeBegin = System.nanoTime(); 
  26.             for(int i =0 ;i<100000;i++){ 
  27.                 BeanUtils.getSimpleProperty(new A(), "a"); 
  28.             } 
  29.             long timeEnd = System.nanoTime(); 
  30.             System.out.println((timeEnd - timeBegin)/1000 
  31.             ); 
  32.         } catch (IllegalAccessException e) { 
  33.             // TODO Auto-generated catch block 
  34.             e.printStackTrace(); 
  35.         } catch (InvocationTargetException e) { 
  36.             // TODO Auto-generated catch block 
  37.             e.printStackTrace(); 
  38.         } catch (NoSuchMethodException e) { 
  39.             // TODO Auto-generated catch block 
  40.             e.printStackTrace(); 
  41.         } 
  42.     } 


一比吓了一跳,效率大概是一百倍左右。怕是由于try块的开销大,本人又把27行注释掉。结论是影响效率的主要是

27行。看来,反射耗资源的说法还真不假。