Java 反射不是一點半點慢!
閱讀本文大概需要 6?分鐘。
作者:張明云
鏈接:https://www.jianshu.com/p/4e2b49fa8ba1
反射真的存在性能問題嗎?
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;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(){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("執(zhí)行直接調(diào)用方法耗時:" + costTime + " 毫秒");costTime = getReflectCallMethodCostTime(executeCount);normalMethodCostTime += costTime;updateResultTextView("執(zhí)行反射調(diào)用方法耗時:" + costTime + " 毫秒");costTime = getNormalFieldCostTime(executeCount);reflectFieldCostTime += costTime;updateResultTextView("執(zhí)行普通調(diào)用實例耗時:" + costTime + " 毫秒");costTime = getReflectCallFieldCostTime(executeCount);normalFieldCostTime += costTime;updateResultTextView("執(zhí)行反射調(diào)用實例耗時:" + costTime + " 毫秒");}updateResultTextView("執(zhí)行直接調(diào)用方法平均耗時:" + reflectMethodCostTime/AVERAGE_COUNT + " 毫秒");updateResultTextView("執(zhí)行反射調(diào)用方法平均耗時:" + normalMethodCostTime/AVERAGE_COUNT + " 毫秒");updateResultTextView("執(zhí)行普通調(diào)用實例平均耗時:" + reflectFieldCostTime/AVERAGE_COUNT + " 毫秒");updateResultTextView("執(zhí)行反射調(diào)用實例平均耗時:" + 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(){public void run(){mExecuteResultTxtView.append(content);mExecuteResultTxtView.append("\n");}});}}

反射的確會導(dǎo)致性能問題;
反射導(dǎo)致的性能問題是否嚴(yán)重跟使用的次數(shù)有關(guān)系,如果控制在100次以內(nèi),基本上沒什么差別,如果調(diào)用次數(shù)超過了100次,性能差異會很明顯;
四種訪問方式,直接訪問實例的方式效率最高;其次是直接調(diào)用方法的方式,耗時約為直接調(diào)用實例的1.4倍;接著是通過反射訪問實例的方式,耗時約為直接訪問實例的3.75倍;最慢的是通過反射訪問方法的方式,耗時約為直接訪問實例的6.2倍;
反射到底慢在哪?
private long getReflectCallMethodCostTime(int count){long startTime = System.currentTimeMillis();ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);Method setmLanguageMethod = null;try{setmLanguageMethod = programMonkey.getClass().getMethod("setmLanguage", String.class);setmLanguageMethod.setAccessible(true);}catch(NoSuchMethodException e){e.printStackTrace();}for(int index = 0 ; index < count; index++){try{setmLanguageMethod.invoke(programMonkey, "Java");}catch(IllegalAccessException e){e.printStackTrace();}catch(InvocationTargetException e){e.printStackTrace();}}return System.currentTimeMillis()-startTime;}private long getReflectCallFieldCostTime(int count){long startTime = System.currentTimeMillis();ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);Field ageField = null;try{ageField = programMonkey.getClass().getDeclaredField("mLanguage");}catch(NoSuchFieldException e){e.printStackTrace();}for(int index = 0 ; index < count; index++){try{ageField.set(programMonkey, "Java");}catch(IllegalAccessException e){e.printStackTrace();}}return System.currentTimeMillis()-startTime;}

private long getReflectCallMethodCostTime(int count){long startTime = System.currentTimeMillis();ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);for(int index = 0 ; index < count; index++){try{Method setmLanguageMethod = programMonkey.getClass().getMethod("setmLanguage", String.class);}catch(NoSuchMethodException e){e.printStackTrace();}}return System.currentTimeMillis()-startTime;}private long getReflectCallFieldCostTime(int count){long startTime = System.currentTimeMillis();ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);for(int index = 0 ; index < count; index++){try{Field ageField = programMonkey.getClass().getDeclaredField("mLanguage");}catch(NoSuchFieldException e){e.printStackTrace();}}return System.currentTimeMillis()-startTime;}

getMethod和getDeclaredField方法會比invoke和set方法耗時;
隨著測試數(shù)量級越大,性能差異的比例越趨于穩(wěn)定;
如果避免反射導(dǎo)致的性能問題?
不要過于頻繁地使用反射,大量地使用反射會帶來性能問題;
通過反射直接訪問實例會比訪問方法快很多,所以應(yīng)該優(yōu)先采用訪問實例的方式。
后記
測試頻繁調(diào)用native方法是否會有明顯的性能問題;
測試同一個方法內(nèi),過多的條件判斷是否會有明顯的性能問題;
測試類的復(fù)雜程度是否會對反射的性能有明顯影響。
推薦閱讀:
基于 token 的多平臺身份認(rèn)證架構(gòu)設(shè)計
微信掃描二維碼,關(guān)注我的公眾號
朕已閱?
評論
圖片
表情

