Java反射到底慢在哪?
閱讀本文大概需要 6?分鐘。
來(lái)自: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 + "毫秒耗時(shí)情況測(cè)試");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(){public void run(){mExecuteResultTxtView.append(content);mExecuteResultTxtView.append("\n");}});}}

反射的確會(huì)導(dǎo)致性能問(wèn)題;
反射導(dǎo)致的性能問(wèn)題是否嚴(yán)重跟使用的次數(shù)有關(guān)系,如果控制在100次以?xún)?nèi),基本上沒(méi)什么差別,如果調(diào)用次數(shù)超過(guò)了100次,性能差異會(huì)很明顯;
四種訪問(wèn)方式,直接訪問(wèn)實(shí)例的方式效率最高;其次是直接調(diào)用方法的方式,耗時(shí)約為直接調(diào)用實(shí)例的1.4倍;接著是通過(guò)反射訪問(wèn)實(shí)例的方式,耗時(shí)約為直接訪問(wèn)實(shí)例的3.75倍;最慢的是通過(guò)反射訪問(wèn)方法的方式,耗時(shí)約為直接訪問(wèn)實(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方法會(huì)比invoke和set方法耗時(shí);
隨著測(cè)試數(shù)量級(jí)越大,性能差異的比例越趨于穩(wěn)定;
不要過(guò)于頻繁地使用反射,大量地使用反射會(huì)帶來(lái)性能問(wèn)題;
通過(guò)反射直接訪問(wèn)實(shí)例會(huì)比訪問(wèn)方法快很多,所以應(yīng)該優(yōu)先采用訪問(wèn)實(shí)例的方式。
測(cè)試頻繁調(diào)用native方法是否會(huì)有明顯的性能問(wèn)題;
測(cè)試同一個(gè)方法內(nèi),過(guò)多的條件判斷是否會(huì)有明顯的性能問(wèn)題;
測(cè)試類(lèi)的復(fù)雜程度是否會(huì)對(duì)反射的性能有明顯影響。
推薦閱讀:
token 過(guò)期后,如何自動(dòng)續(xù)期?
內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬(wàn)并發(fā)、消息隊(duì)列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!
?戳閱讀原文領(lǐng)?。?/span>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??朕已閱?

