您好,登錄后才能下訂單哦!
這篇文章主要介紹了java如何替換switch,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
替換switch
關(guān)鍵字 switch 語句用于多條件判斷, switch 語句的功能類似于 if-else 語句,兩者性能也差不多。因此,不能說 switch 語句會降低系統(tǒng)的性能。但是,在絕大部分情況下,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,實(shí)現(xiàn)相同的程序功能,性能就能有很大的提升空間。
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]; } }
以上代碼使用全新的思路,使用一個連續(xù)的數(shù)組代替了 switch 語句。因?yàn)閷?shù)據(jù)的隨機(jī)訪問是非??斓模辽俸糜?switch 的分支判斷。通過實(shí)驗(yàn),使用switch的語句耗時17860ms,使用數(shù)組的實(shí)現(xiàn)只耗時12590ms,提升了5s多。在軟件開發(fā)中,換一種思路可能會取得更好的效果,比如使用數(shù)組替代switch語句就是就是一個很好的例子。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“java如何替換switch”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。