Java反射到底慢在哪?
點(diǎn)擊上方“碼農(nóng)突圍”,馬上關(guān)注
這里是碼農(nóng)充電第一站,回復(fù)“666”,獲取一份專屬大禮包
真愛,請(qǐng)?jiān)O(shè)置“星標(biāo)”或點(diǎn)個(gè)“在看”

反射真的存在性能問題嗎?
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?+?"毫秒耗時(shí)情況測(cè)試");
????????????????for(int?index?=?0;?index?????????????????????updateResultTextView("第?"?+?(index+1)?+?"?次");
????????????????????costTime?=?getNormalCallCostTime(executeCount);
????????????????????reflectMethodCostTime?+=?costTime;
????????????????????updateResultTextView("執(zhí)行直接調(diào)用方法耗時(shí):"?+?costTime?+?"?毫秒");
????????????????????costTime?=?getReflectCallMethodCostTime(executeCount);
????????????????????normalMethodCostTime?+=?costTime;
????????????????????updateResultTextView("執(zhí)行反射調(diào)用方法耗時(shí):"?+?costTime?+?"?毫秒");
????????????????????costTime?=?getNormalFieldCostTime(executeCount);
????????????????????reflectFieldCostTime?+=?costTime;
????????????????????updateResultTextView("執(zhí)行普通調(diào)用實(shí)例耗時(shí):"?+?costTime?+?"?毫秒");
????????????????????costTime?=?getReflectCallFieldCostTime(executeCount);
????????????????????normalFieldCostTime?+=?costTime;
????????????????????updateResultTextView("執(zhí)行反射調(diào)用實(shí)例耗時(shí):"?+?costTime?+?"?毫秒");
????????????????}
????????????????updateResultTextView("執(zhí)行直接調(diào)用方法平均耗時(shí):"?+?reflectMethodCostTime/AVERAGE_COUNT?+?"?毫秒");
????????????????updateResultTextView("執(zhí)行反射調(diào)用方法平均耗時(shí):"?+?normalMethodCostTime/AVERAGE_COUNT?+?"?毫秒");
????????????????updateResultTextView("執(zhí)行普通調(diào)用實(shí)例平均耗時(shí):"?+?reflectFieldCostTime/AVERAGE_COUNT?+?"?毫秒");
????????????????updateResultTextView("執(zhí)行反射調(diào)用實(shí)例平均耗時(shí):"?+?normalFieldCostTime/AVERAGE_COUNT?+?"?毫秒");
????????????}
????????});
????}
????private?long?getReflectCallMethodCostTime(int?count){
????????long?startTime?=?System.currentTimeMillis();
????????for(int?index?=?0?;?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?????????????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?????????????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?????????????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");
????????????}
????????});
????}
}

反射的確會(huì)導(dǎo)致性能問題; 反射導(dǎo)致的性能問題是否嚴(yán)重跟使用的次數(shù)有關(guān)系,如果控制在100次以內(nèi),基本上沒什么差別,如果調(diào)用次數(shù)超過了100次,性能差異會(huì)很明顯; 四種訪問方式,直接訪問實(shí)例的方式效率最高;其次是直接調(diào)用方法的方式,耗時(shí)約為直接調(diào)用實(shí)例的1.4倍;接著是通過反射訪問實(shí)例的方式,耗時(shí)約為直接訪問實(shí)例的3.75倍;最慢的是通過反射訪問方法的方式,耗時(shí)約為直接訪問實(shí)例的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?????????????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?????????????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?????????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?????????try{
????????????Field?ageField?=?programMonkey.getClass().getDeclaredField("mLanguage");
????????}catch(NoSuchFieldException?e){
????????????e.printStackTrace();
????????}
????}
????return?System.currentTimeMillis()-startTime;
}

getMethod和getDeclaredField方法會(huì)比invoke和set方法耗時(shí); 隨著測(cè)試數(shù)量級(jí)越大,性能差異的比例越趨于穩(wěn)定;
如果避免反射導(dǎo)致的性能問題?
不要過于頻繁地使用反射,大量地使用反射會(huì)帶來性能問題; 通過反射直接訪問實(shí)例會(huì)比訪問方法快很多,所以應(yīng)該優(yōu)先采用訪問實(shí)例的方式。
后記
測(cè)試頻繁調(diào)用native方法是否會(huì)有明顯的性能問題; 測(cè)試同一個(gè)方法內(nèi),過多的條件判斷是否會(huì)有明顯的性能問題; 測(cè)試類的復(fù)雜程度是否會(huì)對(duì)反射的性能有明顯影響。
最近熱文
? ?應(yīng)屆碩士被建議破格授予博士學(xué)位!這個(gè)學(xué)霸三年發(fā)了16篇SCI ???面試官寫了個(gè)雙冒號(hào)::問我這是什么語(yǔ)法?Java中有這玩意? ???亞馬遜機(jī)器人公司副總離職,加入23歲華裔「天才少年」創(chuàng)立的AI獨(dú)角獸 ???干掉 "ZooKeeper",阿里為什么不用 ZK 做服務(wù)發(fā)現(xiàn)? 最近整理了一份大廠算法刷題指南,包括一些刷題技巧,在知乎上已經(jīng)有上萬贊。同時(shí)還整理了一份6000頁(yè)面試筆記。關(guān)注下面公眾號(hào),在公眾號(hào)內(nèi)回復(fù)「刷題」,即可免費(fèi)獲?。?span style="letter-spacing: 0.544px;-webkit-tap-highlight-color: rgba(0, 0, 0, 0);font-weight: bolder;">回復(fù)「加群」,可以邀請(qǐng)你加入讀者群!
明天見(??ω??)??
評(píng)論
圖片
表情
