Java反射到底慢在哪?
1、比 MyBatis 快 100 倍,天生支持聯(lián)表! 2、這份Java日志格式規(guī)范,強(qiáng)?。?/a> 3、離職就打低績效,這樣對嗎? 4、一個(gè)高中生的編程自學(xué)經(jīng)歷 5、巨坑,常見的 update 語句很容易造成Bug
來源: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;@Overrideprotected 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(){@Overridepublic void run(){long costTime = 0;int executeCount = Integer.parseInt(mExecuteCountEditTxt.getText().toString());long reflectMethodCostTime=0,normalMethodCostTime=0,reflectFieldCostTime=0,normalFieldCostTime=0;updateResultTextView(executeCount + "毫秒耗時(shí)情況測試");for(int index = 0; index < AVERAGE_COUNT; 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 < 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(){@Overridepublic void run(){mExecuteResultTxtView.append(content);mExecuteResultTxtView.append("\n");}});}}

反射的確會導(dǎo)致性能問題; 反射導(dǎo)致的性能問題是否嚴(yán)重跟使用的次數(shù)有關(guān)系,如果控制在100次以內(nèi),基本上沒什么差別,如果調(diào)用次數(shù)超過了100次,性能差異會很明顯; 四種訪問方式,直接訪問實(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 < 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í); 隨著測試數(shù)量級越大,性能差異的比例越趨于穩(wěn)定;
不要過于頻繁地使用反射,大量地使用反射會帶來性能問題; 通過反射直接訪問實(shí)例會比訪問方法快很多,所以應(yīng)該優(yōu)先采用訪問實(shí)例的方式。
測試頻繁調(diào)用native方法是否會有明顯的性能問題; 測試同一個(gè)方法內(nèi),過多的條件判斷是否會有明顯的性能問題; 測試類的復(fù)雜程度是否會對反射的性能有明顯影響。
往期熱門文章:
1、巨坑,常見的 update 語句很容易造成Bug 2、完爆90%的數(shù)據(jù)庫性能毛病! 3、Spring Boot性能太差,教你幾招輕松搞定 4、Fastjson 2 來了,性能繼續(xù)提升,還能再戰(zhàn)十年 5、笑死!程序員延壽指南開源了 6、用 Dubbo 傳輸文件?被老板一頓揍! 7、45 個(gè) Git 經(jīng)典操作場景,專治不會合代碼! 8、@Transactional 注解失效的3種原因及解決辦法 9、小學(xué)生們在B站講算法,網(wǎng)友:我只會阿巴阿巴 10、Spring爆出比Log4j2還大的漏洞?
評論
圖片
表情
