Why is if (variable1 % variable2 == 0) inefficient?

前端 未结 4 1292
我寻月下人不归
我寻月下人不归 2021-01-29 18:51

I am new to java, and was running some code last night, and this really bothered me. I was building a simple program to display every X outputs in a for loop, and I noticed a MA

4条回答
  •  逝去的感伤
    2021-01-29 19:30

    I am also surprised by seeing the performance of the above codes. It's all about the time taken by the compiler for executing the program as per the declared variable. In the second (inefficient) example:

    for (long i = startNum; i <= stopNum; i++) {
        if (i % progressCheck == 0) {
            System.out.println(i)
        }
    }
    

    You are performing the modulus operation between two variables. Here, compiler has to check the value of stopNum and progressCheck to go to the specific memory block located for these variables every time after each iteration because it is a variable and its value might be change.

    That's why after each iteration compiler went to the memory location to check the latest value of the variables. Therefore at the compile time the compiler was not able to create efficient byte code.

    In the first code example, you are performing modulus operator between a variable and a constant numeric value which is not going to change within execution and compiler no need to check the value of that numeric value from the memory location. That's why compiler was able to create efficient byte code. If you declare progressCheck as a final or as a final static variable then at the time of run-time/compile-time compiler know that it's a final variable and its value not going to change then compiler replace the progressCheck with 50000 in code:

    for (long i = startNum; i <= stopNum; i++) {
        if (i % 50000== 0) {
            System.out.println(i)
        }
    }
    

    Now you can see that this code also looks like the first (efficient) code example. The performance of first code and as we mentioned above both code will work efficiently. There will not be much difference in execution time of either code example.

提交回复
热议问题