The question of which is better, if or switch

Introduction

――How many times have you written if since you have coded? Lol ――Even if you write tens of thousands of times, you sometimes wonder whether to use switch or if, right? ?? (I may be worried)

My current selection criteria

-When choosing an if statement:&&And||When you want --When switching: When there are many choices --When you don't need to switch: Ternary operator ――The rest is a feeling if you are worried ――I chose it with a feeling like that, but one day I thought

Which one will perform better when you play either one?

――If you are interested, you should measure it, right? I think --Now, execute!

What you have prepared

Table of contents (what you expect to do at the time of writing the table of contents)

--Run a branch in a loop of about 100 times --If there is no performance difference after 100 times, increase the number of digits one by one. ――If you are satisfied to some extent, increase the conditions ――If you are satisfied with increasing the conditions, do a character string and number pattern ――I will do it like this

Practice

Run the branch in a loop of about 100 times

--The executed code is below

CheckPerformance.java


import java.util.stream.IntStream;

public class CheckPerformance {

    public static void main(String[] args) {
        Long start = System.currentTimeMillis();
        //if execution
        IntStream.rangeClosed(0, 100).forEach(i -> {
            if (i % 2 == 0) {
                System.out.println("Is an even number");
            } else if (i % 2 == 1) {
                System.out.println("Is odd");
            } else {
                System.out.println("Other");
            }
        });

        //Switch execution
        IntStream.rangeClosed(0, 100).forEach(i -> {
            switch (i % 2) {
                case 0:
                    System.out.println("Is an even number");
                    break;
                case 1:
                    System.out.println("Is odd");
                    break;
                default:
                    System.out.println("Other");
                    break;
            }
        });
        Long end = System.currentTimeMillis();
        System.out.println(end - start + "ms");
    }
}

--The execution result is as follows

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 7ms 12ms
Second time 15ms 10ms
Third time 13ms 12ms
4th 8ms 15ms
5th time 10ms 10ms

Verification

――I ran it several times, but it became like a luck game, so I decided that it would be difficult to verify the performance difference with 100 times. ――In short, it's just an error

Run a branch in a loop of 1,000 times

--Source omitted --The execution result is as follows

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 36ms 39ms
Second time 33ms 35ms
Third time 31ms 28ms
4th 38ms 39ms
5th time 38ms 34ms

Verification

――Hmm, it is subtle to verify the performance difference even 1,000 times ――I still feel that it is in the category of error here.

Run the branch in 10,000 loops

--The source is (ry --The execution result is as follows

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 133ms 119ms
Second time 147ms 136ms
Third time 116ms 121ms
4th 135ms 130ms
5th time 128ms 136ms

Verification

――Hmm, even 10,000 times ... (ry

Run the branch in 100,000 loops

--The source is (ry --The execution result is as follows

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 903ms 917ms
Second time 947ms 885ms
Third time 1012ms 964ms
4th 1109ms 947ms
5th time 943ms 884ms

Verification

――I feel that there was a slight difference in performance after 100,000 times. ――The switch exceeded 1 second 0 times, but there are 2 ifs. ――However, the error may be an error, and if you look only at the average value, the switch may be faster? The hypothesis was reached ――But I'm a little worried, so I'll add another digit and execute it.

Run a branch in a loop of 1,000,000 times

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 6366ms 6339ms
Second time 6410ms 6396ms
Third time 6794ms 6298ms
4th 6730ms 6248ms
5th time 6823ms 6495ms

Verification

--You can see the performance difference at 1,000,000 times. ――I feel that the speed of the switch did not vary, and the result was that it was slightly faster. ――However, since the performance difference is only this much after doing 1 million cases, it seems that it is difficult to be aware of the performance difference in everyday use.

Increase the number of branches

――So, I'm satisfied to some extent, so I will increase the number of branches. ――From here, I found that it doesn't make much sense to do 100 cases, so I will carry out with 1 million cases.

First, make three branches

--Omit the source --The execution result is as follows

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 6348ms 6476ms
Second time 6751ms 6354ms
Third time 6461ms 6324ms
4th 6500ms 6411ms
5th time 6537ms 6646ms

Verification

――You can see the difference in performance after 3 branches. ――When you look at the average value, switch is a little faster, isn't it? ――However, it may be an error, so increase the number of branches.

Make 5 branches

――I chose five because of the convenience of calculation and my mood. --The execution result is as follows

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 6528ms 6279ms
Second time 6452ms 6507ms
Third time 6661ms 6599ms
4th 6501ms 6589ms
5th time 6608ms 6322ms

Verification

--You can see the difference in performance after 5 branches. ――Hmm, is it within the margin of error?

Conclusion

There is almost no difference in performance between if and switch!

――It's a matter of catching the title, but it's my conclusion ――I have only executed 1 million cases, but I am aware that it may change if more are added. ――However, it seems that the performance does not change significantly between if and switch depending on the number of branches and the number of processes, so I feel that the decision to select an implementation that is easier to read is correct. ――If something is wrong, or if you should verify it more like this, please leave a comment or an edit request!

Postscript

--In the comment, you pointed out that println is too heavy, so I tried to fix it.

Main.java


import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {

        long start = System.currentTimeMillis();

        IntStream.rangeClosed(0, 10000000).forEach(
                num -> {
                    if (num % 2 == 0) {
                        int num2 = 2;
                    } else if (num % 2 == 1){
                        int num3 = 2;
                    } else {
                        int num4 = 2;
                    }
                }
        );
        IntStream.rangeClosed(0, 10000000).forEach(
                num -> {
                    switch (num % 2) {
                        case 0:
                            int num2 = 2;
                            break;
                        case 1:
                            int num3 = 2;
                            break;
                        default:
                            int num4 = 2;
                            break;
                    }
                }
                        );
        long end = System.currentTimeMillis();
        System.out.println((end - start)  + "ms");

    }
}

--Since I / O processing is heavy, I just declared variables in the for statement for the time being. ――Please tell me if there is a better way

Execution result

Xth time number of seconds to execute if Number of seconds to execute the switch
1st time 79ms 70ms
Second time 81ms 64ms
Third time 90ms 62ms
4th 86ms 67ms
5th time 83ms 63ms

――There was a performance difference of about 20ms after turning 10 million cases, but I wonder if there is no problem with the conclusion that there is almost no difference. --Bytecode verification will be done at a later date!

Recommended Posts

The question of which is better, if or switch
Which is better, Kotlin or Java in the future?
Java: The problem of which is faster, stream or loop
Which is faster, size or 0, as the argument of List # toArray?
[6 selections of form tool comparison] Which is better, open source or commercial?
Switch the version of bundler
Is the method of the primitive specialized IntFunction apply or applyAsInt?
Which is better, generalization or delegation, when there are overlaps?
Which Java HTTP client is better?
'% 02d' What is the percentage of% 2?
What is @Override or @SuppressWarnings ("SleepWhileInLoop") in front of the function? ?? ??
Change the conversation depending on which day of the week is today
Get the type of an array element to determine if it is an array
[Java] Check if the character string is composed only of blanks (= Blank)
What is testing? ・ About the importance of testing
What is the data structure of ActionText?
Basics of java basics ② ~ if statement and switch statement ~
[Swift] If the support of the application is iOS 11 or later, it was not necessary to use Int and Int64 properly
What is JSP? ~ Let's know the basics of JSP !! ~
ActiveSupport underscore is not the inverse of camelize
The order of Java method modifiers is fixed
Which is faster, method reference or lambda expression
The official name of Spring MVC is Spring Web MVC
Which is faster, Array # sample or Random # rand?
[August 2020] If the installation of cool.io / puma fails
First touch of the Files class (or Java 8)
The end of catastrophic programming # 03 "Comparison of integers, if" a> b ", assume that it is" a --b> 0 ""