<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Java 反射到底慢在哪?

          共 1915字,需瀏覽 4分鐘

           ·

          2020-10-18 23:04

          Java技術(shù)棧

          www.javastack.cn

          關(guān)注閱讀更多優(yōu)質(zhì)文章



          反射具體是怎么影響性能的?這引起了我的反思。關(guān)于 Java 反射系列文章可以關(guān)注公眾號(hào)Java技術(shù)棧搜索閱讀。

          是啊,在闡述某個(gè)觀點(diǎn)時(shí)確實(shí)有必要說明原因,并且證明這個(gè)觀點(diǎn)是對(duì)的,雖然反射影響性能人盡皆知,我曾經(jīng)也真的研究過反射是否存在性能問題,但并沒有在寫文章的時(shí)候詳細(xì)說明。

          這讓我想到網(wǎng)上很多信息只會(huì)告訴你結(jié)論,并不會(huì)說明原因,導(dǎo)致很多學(xué)到的東西都是死記硬背,而不是真正掌握,別人一問或者自己親身遇到同樣的問題時(shí),傻眼了。

          反射真的存在性能問題嗎?

          還是使用上篇文章的demo,為了放大問題,找到共性,采用逐漸擴(kuò)大測試次數(shù)、每次測試多次取平均值的方式,針對(duì)同一個(gè)方法分別就直接調(diào)用該方法、反射調(diào)用該方法、直接調(diào)用該方法對(duì)應(yīng)的實(shí)例、反射調(diào)用該方法對(duì)應(yīng)的實(shí)例分別從1-1000000,每隔一個(gè)數(shù)量級(jí)測試一次:

          測試代碼如下(Person、ICompany、ProgramMonkey這三個(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í)情況測試");
          ????????????????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");
          ????????????}
          ????????});
          ????}
          }

          測試結(jié)果如下:

          反射性能測試結(jié)果

          測試結(jié)論:

          • 反射的確會(huì)導(dǎo)致性能問題;推薦看下Java反射是什么?》夠了。
          • 反射導(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倍;

          反射到底慢在哪?

          跟蹤源碼可以發(fā)現(xiàn),四個(gè)方法中都存在實(shí)例化ProgramMonkey的代碼,所以可以排除是這句話導(dǎo)致的不同調(diào)用方式產(chǎn)生的性能差異;通過反射調(diào)用方法中調(diào)用了setAccessible方法,但該方法純粹只是設(shè)置屬性值,不會(huì)產(chǎn)生明顯的性能差異;所以最有可能產(chǎn)生性能差異的只有g(shù)etMethod和getDeclaredField、invoke和set方法了,下面分別就這兩組方法進(jìn)行測試,找到具體慢在哪?

          首先測試invoke和set方法,修改getReflectCallMethodCostTime和getReflectCallFieldCostTime方法的代碼如下:

          ????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;
          ????}

          沿用上面的測試方法,測試結(jié)果如下:

          invoke和set

          修改getReflectCallMethodCostTime和getReflectCallFieldCostTime方法的代碼如下,對(duì)getMethod和getDeclaredField進(jìn)行測試

          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;
          }

          沿用上面的測試方法,測試結(jié)果如下:

          getMethod和getDeclaredField

          測試結(jié)論:

          • getMethod和getDeclaredField方法會(huì)比invoke和set方法耗時(shí);
          • 隨著測試數(shù)量級(jí)越大,性能差異的比例越趨于穩(wěn)定;

          由于測試的這四個(gè)方法最終調(diào)用的都是native方法,無法進(jìn)一步跟蹤。

          個(gè)人猜測應(yīng)該是和在程序運(yùn)行時(shí)操作class有關(guān),比如需要判斷是否安全?是否允許這樣操作?入?yún)⑹欠裾_?是否能夠在虛擬機(jī)中找到需要反射的類?主要是這一系列判斷條件導(dǎo)致了反射耗時(shí);也有可能是因?yàn)檎{(diào)用natvie方法,需要使用JNI接口,導(dǎo)致了性能問題(參照Log.java、System.out.println,都是調(diào)用native方法,重復(fù)調(diào)用多次耗時(shí)很明顯)。

          如果避免反射導(dǎo)致的性能問題?

          通過上面的測試可以看出,過多地使用反射,的確會(huì)存在性能問題,但如果使用得當(dāng),所謂反射導(dǎo)致性能問題也就不是問題了,關(guān)于反射對(duì)性能的影響,參照下面的使用原則,并不會(huì)有什么明顯的問題:

          • 不要過于頻繁地使用反射,大量地使用反射會(huì)帶來性能問題;
          • 通過反射直接訪問實(shí)例會(huì)比訪問方法快很多,所以應(yīng)該優(yōu)先采用訪問實(shí)例的方式。

          后記

          上面的測試并不全面,但在一定程度上能夠反映出反射的確會(huì)導(dǎo)致性能問題,也能夠大概知道是哪個(gè)地方導(dǎo)致的問題。如果后面有必要進(jìn)一步測試,我會(huì)從下面幾個(gè)方面作進(jìn)一步測試:

          • 測試頻繁調(diào)用native方法是否會(huì)有明顯的性能問題;

          • 測試同一個(gè)方法內(nèi),過多的條件判斷是否會(huì)有明顯的性能問題;

          • 測試類的復(fù)雜程度是否會(huì)對(duì)反射的性能有明顯影響。


          本文作者:張明云
          鏈接:https://www.jianshu.com/p/4e2b49fa8ba1




          關(guān)注Java技術(shù)棧看更多干貨



          戳原文,獲取精選面試題!
          瀏覽 35
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  伊人日日| 999综合网 | 免费人人操 | 操逼视频网站免费 | 北条麻纪一区二区三区在线视频 |