反射真的存在性能问题吗?

通过对不同调用方式的性能测试,发现反射确实存在性能问题,尤其是在调用次数超过100次时,性能差异显著。直接访问实例的效率最高,而通过反射访问方法的方式最慢,耗时约为直接访问实例的6.2倍。建议在需要考虑性能的应用场景中谨慎使用反射。
摘要由CSDN通过智能技术生成

还是使用上篇文章的demo,为了放大问题,找到共性,采用逐渐扩大测试次数、每次测试多次取平均值的方式,针对同一个方法分别就直接调用该方法、反射调用该方法、直接调用该方法对应的实例、反射调用该方法对应的实例分别从1-1000000,每隔一个数量级测试一次:

测试代码如下(Person、ICompany、ProgramMonkey这三个类已在之前的文章中贴出):

public class ReflectionPerformanceActivity extends Activity{
    private TextView mExecuteResultTxtView = null;
    private EditText mExecuteCountEditTxt = null;
    private Executor mPerformanceExecutor = Executors.newSingleThreadExecutor();
    private static final int AVERAGE_COUNT = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reflection_performance_layout);
        mExecuteResultTxtView = (TextView)findViewById(R.id.executeResultTxtId);
        mExecuteCountEditTxt = (EditText)findViewById(R.id.executeCountEditTxtId);
    }

    public void onClick(View v){
        switch(v.getId()){
            case R.id.executeBtnId:{
                execute();
            }
            break;
            default:{

            }
            break;
        }
    }

    private void execute(){
        mExecuteResultTxtView.setText("");
        mPerformanceExecutor.execute(new Runnable(){
            @Override
            public void run(){
                long costTime = 0;
                int executeCount = Integer.parseInt(mExecuteCountEditTxt.getText().toString());
                long reflectMethodCostTime=0,normalMethodCostTime=0,reflectFieldCostTime=0,normalFieldCostTime=0;
                updateResultTextView(executeCount + "毫秒耗时情况测试");
                for(int index = 0; index < AVERAGE_COUNT; index++){
                    updateResultTextView("第 " + (index+1) + " 次");
                    costTime = getNormalCallCostTime(executeCount);
                    reflectMethodCostTime += costTime;
                    updateResultTextView("执行直接调用方法耗时:" + costTime + " 毫秒");
                    costTime = getReflectCallMethodCostTime(executeCount);
                    normalMethodCostTime += costTime;
                    updateResultTextView("执行反射调用方法耗时:" + costTime + " 毫秒");
                    costTime = getNormalFieldCostTime(executeCount);
                    reflectFieldCostTime += costTime;
                    updateResultTextView("执行普通调用实例耗时:" + costTime + " 毫秒");
                    costTime = getReflectCallFieldCostTime(executeCount);
                    normalFieldCostTime += costTime;
                    updateResultTextView("执行反射调用实例耗时:" + costTime + " 毫秒");
                }

                updateResultTextView("执行直接调用方法平均耗时:" + reflectMethodCostTime/AVERAGE_COUNT + " 毫秒");
                updateResultTextView("执行反射调用方法平均耗时:" + normalMethodCostTime/AVERAGE_COUNT + " 毫秒");
                updateResultTextView("执行普通调用实例平均耗时:" + reflectFieldCostTime/AVERAGE_COUNT + " 毫秒");
                updateResultTextView("执行反射调用实例平均耗时:" + normalFieldCostTime/AVERAGE_COUNT + " 毫秒");
            }
        });
    }

    private long getReflectCallMethodCostTime(int count){
        long startTime = System.currentTimeMillis();
        for(int index = 0 ; index < count; index++){
            ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
            try{
                Method setmLanguageMethod = programMonkey.getClass().getMethod("setmLanguage", String.class);
                setmLanguageMethod.setAccessible(true);
                setmLanguageMethod.invoke(programMonkey, "Java");
            }catch(IllegalAccessException e){
                e.printStackTrace();
            }catch(InvocationTargetException e){
                e.printStackTrace();
            }catch(NoSuchMethodException e){
                e.printStackTrace();
            }
        }

        return System.currentTimeMillis()-startTime;
    }

    private long getReflectCallFieldCostTime(int count){
        long startTime = System.currentTimeMillis();
        for(int index = 0 ; index < count; index++){
            ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
            try{
                Field ageField = programMonkey.getClass().getDeclaredField("mLanguage");
                ageField.set(programMonkey, "Java");
            }catch(NoSuchFieldException e){
                e.printStackTrace();
            }catch(IllegalAccessException e){
                e.printStackTrace();
            }
        }

        return System.currentTimeMillis()-startTime;
    }

    private long getNormalCallCostTime(int count){
        long startTime = System.currentTimeMillis();
        for(int index = 0 ; index < count; index++){
            ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
            programMonkey.setmLanguage("Java");
        }

        return System.currentTimeMillis()-startTime;
    }

    private long getNormalFieldCostTime(int count){
        long startTime = System.currentTimeMillis();
        for(int index = 0 ; index < count; index++){
            ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
            programMonkey.mLanguage = "Java";
        }

        return System.currentTimeMillis()-startTime;
    }

    private void updateResultTextView(final String content){
        ReflectionPerformanceActivity.this.runOnUiThread(new Runnable(){
            @Override
            public void run(){
                mExecuteResultTxtView.append(content);
                mExecuteResultTxtView.append("\n");
            }
        });
    }
}

测试结果如下:

Java 反射到底慢在哪?

 

反射性能测试结果

测试结论:

  • 反射的确会导致性能问题;推荐看下《Java反射是什么?》够了。
  • 反射导致的性能问题是否严重跟使用的次数有关系,如果控制在100次以内,基本上没什么差别,如果调用次数超过了100次,性能差异会很明显;
  • 四种访问方式,直接访问实例的方式效率最高;其次是直接调用方法的方式,耗时约为直接调用实例的1.4倍;接着是通过反射访问实例的方式,耗时约为直接访问实例的3.75倍;最慢的是通过反射访问方法的方式,耗时约为直接访问实例的6.2倍;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值