Home  >  Article  >  Java  >  How to replace switch in java

How to replace switch in java

王林
王林forward
2023-05-16 21:49:041368browse

Replace switch

Keyword switch statement is used for multi-condition judgment. The function of switch statement is similar to if-else statement, and the performance of the two is similar. Therefore, it cannot be said that the switch statement will reduce the performance of the system. However, in most cases, there is still room for performance improvement in the switch statement.

Look at the following example:

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

As far as branch logic is concerned, the performance of this switch mode is not bad. But if you use a new idea to replace switch and achieve the same program functions, there will be a lot of room for improvement in performance.

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

The above code uses a new idea, using a continuous array instead of the switch statement. Because random access to data is very fast, at least better than switch branch judgment. Through experiments, the statement using switch takes 17860ms, and the implementation using array only takes 12590ms, which is an improvement of more than 5s. In software development, changing your thinking may achieve better results. For example, using an array instead of a switch statement is a good example.

The above is the detailed content of How to replace switch in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete