<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反射到底慢在哪?不看后悔

          共 1878字,需瀏覽 4分鐘

           ·

          2020-09-23 10:54

          轉自:jianshu.com/p/4e2b49fa8ba1

          反射具體是怎么影響性能的?這引起了我的反思。是啊,在闡述某個觀點時確實有必要說明原因,并且證明這個觀點是對的,雖然反射影響性能人盡皆知,我曾經也真的研究過反射是否存在性能問題,但并沒有在寫文章的時候詳細說明。這讓我想到網上很多信息只會告訴你結論,并不會說明原因,導致很多學到的東西都是死記硬背,而不是真正掌握,別人一問或者自己親身遇到同樣的問題時,傻眼了。

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

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

          測試代碼如下(Person、ICompany、ProgramMonkey這三個類已在之前的文章中貼出):

          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?+?"毫秒耗時情況測試");
          ????????????????for(int?index?=?0;?index?????????????????????updateResultTextView("第?"?+?(index+1)?+?"?次");
          ????????????????????costTime?=?getNormalCallCostTime(executeCount);
          ????????????????????reflectMethodCostTime?+=?costTime;
          ????????????????????updateResultTextView("執(zhí)行直接調用方法耗時:"?+?costTime?+?"?毫秒");
          ????????????????????costTime?=?getReflectCallMethodCostTime(executeCount);
          ????????????????????normalMethodCostTime?+=?costTime;
          ????????????????????updateResultTextView("執(zhí)行反射調用方法耗時:"?+?costTime?+?"?毫秒");
          ????????????????????costTime?=?getNormalFieldCostTime(executeCount);
          ????????????????????reflectFieldCostTime?+=?costTime;
          ????????????????????updateResultTextView("執(zhí)行普通調用實例耗時:"?+?costTime?+?"?毫秒");
          ????????????????????costTime?=?getReflectCallFieldCostTime(executeCount);
          ????????????????????normalFieldCostTime?+=?costTime;
          ????????????????????updateResultTextView("執(zhí)行反射調用實例耗時:"?+?costTime?+?"?毫秒");
          ????????????????}

          ????????????????updateResultTextView("執(zhí)行直接調用方法平均耗時:"?+?reflectMethodCostTime/AVERAGE_COUNT?+?"?毫秒");
          ????????????????updateResultTextView("執(zhí)行反射調用方法平均耗時:"?+?normalMethodCostTime/AVERAGE_COUNT?+?"?毫秒");
          ????????????????updateResultTextView("執(zhí)行普通調用實例平均耗時:"?+?reflectFieldCostTime/AVERAGE_COUNT?+?"?毫秒");
          ????????????????updateResultTextView("執(zhí)行反射調用實例平均耗時:"?+?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");
          ????????????}
          ????????});
          ????}
          }

          測試結果如下:


          反射性能測試結果

          測試結論:

          反射的確會導致性能問題;
          反射導致的性能問題是否嚴重跟使用的次數(shù)有關系,如果控制在100次以內,基本上沒什么差別,如果調用次數(shù)超過了100次,性能差異會很明顯;

          四種訪問方式,直接訪問實例的方式效率最高;其次是直接調用方法的方式,耗時約為直接調用實例的1.4倍;接著是通過反射訪問實例的方式,耗時約為直接訪問實例的3.75倍;最慢的是通過反射訪問方法的方式,耗時約為直接訪問實例的6.2倍;

          ?友情推薦下歡哥的開源項目:https://github.com/yinjihuan/kitty

          Spring Cloud & Spring Cloud Alibaba 基礎框架,內置了 Cat 監(jiān)控,互聯(lián)網公司落地 Spring Cloud 架構必備。


          反射到底慢在哪?

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

          首先測試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;
          ????}

          沿用上面的測試方法,測試結果如下:


          invoke和set

          修改getReflectCallMethodCostTime和getReflectCallFieldCostTime方法的代碼如下,對getMethod和getDeclaredField進行測試

          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

          測試結論:

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

          由于測試的這四個方法最終調用的都是native方法,無法進一步跟蹤。個人猜測應該是和在程序運行時操作class有關,比如需要判斷是否安全?是否允許這樣操作?入參是否正確?是否能夠在虛擬機中找到需要反射的類?主要是這一系列判斷條件導致了反射耗時;也有可能是因為調用natvie方法,需要使用JNI接口,導致了性能問題(參照Log.java、System.out.println,都是調用native方法,重復調用多次耗時很明顯)。

          如何避免反射導致的性能問題?

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

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

          后記

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

          • 測試頻繁調用native方法是否會有明顯的性能問題;
          • 測試同一個方法內,過多的條件判斷是否會有明顯的性能問題;
          • 測試類的復雜程度是否會對反射的性能有明顯影響。


          我整理了一份很全的學習資料,感興趣的可以微信搜索「猿天地」,回復關鍵字 「學習資料」獲取我整理好了的 Spring Cloud,Spring Cloud Alibaba,Sharding-JDBC 分庫分表,任務調度框架 XXL-JOB,MongoDB,爬蟲等相關資料。


          后臺回復?學習資料?領取學習視頻


          如有收獲,點個在看,誠摯感謝

          瀏覽 32
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <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>
                  免费看片AV | 天天做天天添 | 黄色操逼视频免费看 | 亚洲无码蜜桃视频 | 国产www在线观看 |