现在开源框架,为了减少代码耦合度,一般用反射的方法来实现对类方法的查找等。但反射的效率究竟比直接取数据有多大差别。今天,做了个小实验。还请各位高手多多指教。直接来代码:
基本类:
- package test;
- import java.util.ArrayList;
- import java.util.List;
- public class A {
- private int a ;
- private String b;
- private List c;
- public A(){
- this.a = 10;
- this.b = "abcde";
- c = new ArrayList();
- c.add("aaa");
- c.add("bbb");
- }
- public int getA() {
- return a++;
- }
- public void setA(int a) {
- this.a = a;
- }
- public String getB() {
- return b;
- }
- public void setB(String b) {
- this.b = b;
- }
- public List getC() {
- return c;
- }
- public void setC(List c) {
- this.c = c;
- }
- }
测试类:(引入beanUtil类)
- package test;
- import java.lang.reflect.InvocationTargetException;
- import org.apache.commons.beanutils.BeanUtils;
- public class testReflect {
- public static void main(String[] args){
- testReflect tr = new testReflect();
- tr.CommonTest();
- tr.ReflectTest();
- }
- public static void CommonTest(){
- A a = new A();
- long timeBegin = System.nanoTime();
- for(int i =0 ;i<100000;i++){
- a.getA();
- }
- long timeEnd = System.nanoTime();
- System.out.println((timeEnd - timeBegin)/1000
- );
- }
- public static void ReflectTest(){
- try {
- long timeBegin = System.nanoTime();
- for(int i =0 ;i<100000;i++){
- BeanUtils.getSimpleProperty(new A(), "a");
- }
- long timeEnd = System.nanoTime();
- System.out.println((timeEnd - timeBegin)/1000
- );
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
一比吓了一跳,效率大概是一百倍左右。怕是由于try块的开销大,本人又把27行注释掉。结论是影响效率的主要是
27行。看来,反射耗资源的说法还真不假。
转载于:https://blog.51cto.com/liubo/600257