首頁 > Java > java教程 > 主體

java如何替換switch

王林
發布: 2023-05-16 21:49:04
轉載
1249 人瀏覽過

取代switch

關鍵字 switch 語句用於多條件判斷, switch 語句的功能類似於 if-else 語句,兩者效能也差不多。因此,不能說 switch  語句會降低系統的效能。但是,在絕大部分情況下,switch 語句還是有效能提升空間的。

來看下面的範例:

public static void main(String[] args) {                 long start = System.currentTimeMillis();                 int re = 0;                 for (int i = 0;i<1000000;i++){             re = switchInt(i);             System.out.println(re);         }         System.out.println(System.currentTimeMillis() - start+"毫秒");//17860     }         public static int switchInt(int z){                    int i = z%10+1;                    switch (i){                        case 1:return 3;                        case 2:return 6;                        case 3:return 7;                        case 4:return 8;                        case 5:return 10;                        case 6:return 16;                        case 7:return 18;                        case 8:return 44;                        default:return -1;      }   }
登入後複製

就分支邏輯而言,這種 switch 模式的效能並不差。但如果換一種新的思路取代switch,實現相同的程式功能,效能就能有很大的提升空間。

public static void main(String[] args) {                 long start = System.currentTimeMillis();                 int re = 0;                 int[] sw = new int[]{0,3,6,7,8,10,16,18,44};                 for (int i = 0;i<1000000;i++){             re = arrayInt(sw,i);             System.out.println(re);         }         System.out.println(System.currentTimeMillis() - start+"毫秒");//12590     }         public static int arrayInt(         int[] sw,int z){                 int i = z%10+1;                 if (i>7 || i<1){                        return -1;         }else {                        return sw[i];         }     }
登入後複製

以上程式碼使用全新的思路,使用一個連續的陣列取代了 switch 語句。因為對資料的隨機存取是非常快的,至少好於 switch  的分支判斷。透過實驗,使用switch的語句耗時17860ms,使用陣列的實作只耗時12590ms,提升了5s多。在軟體開發中,換個想法可能會取得更好的效果,例如使用陣列取代switch語句就是就是一個很好的例子。

以上是java如何替換switch的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!