Is short-circuit evaluation really fast? Difference between && and & in Java

What is short-circuit evaluation?

If you study Java a little, you will come up with something called "short-circuit evaluation". this is&&Or||In a logical operator such as, when the left side is evaluated, the boolean value of the entire expression is determined and if it is not necessary to evaluate the right side, the right side is not evaluated. See the following example.

boolean flag1 = false;
boolean flag2 = false;
if(flag1 && flag2){
    System.out.println("Both variables are true.");
}

In this program, flag1 and flag2 must both be true in order for the conditional branch on the third line to execute inside the curly braces block. This time flag1 is false, so you can see that you don't have to go inside the curly braces block without having to check the boolean value of flag2. In such a situation, the short-circuit evaluation is a function that automatically prevents the evaluation of flag2.

Difference between && and &

Java has two similar operators, && and &. The two operators have almost the same functionality, but with some differences. As mentioned earlier, the operator && works as a short-circuit evaluation function. However, short-circuit evaluation does not work for &. That is, & evaluates the value on the right-hand side even in situations where it is not necessary to evaluate the value on the right-hand side.

Is short-circuit evaluation really fast?

Java reference books and websites say that && is faster because it doesn't do extra evaluation. When I read that description, I was wondering. "Since it is a different process, is it really faster just to pass the process on the right side?" So I actually tried to verify the difference in processing speed between && and &.

Verification program

Program for short-circuit evaluation

Test1


long start = System.currentTimeMillis();
boolean flag1 = false;
boolean flag2 = false;

for(long i=0; i<10000000000l; i++) {
    if(flag1 && flag2) {
        System.out.print("");
    }
}

long end = System.currentTimeMillis();
System.out.println("Execution time" + (end - start)  + "ms");

&& is used in the conditional expression of the if statement.

Programs that do not perform short-circuit evaluation

Test2


long start = System.currentTimeMillis();
boolean flag1 = false;
boolean flag2 = false;

for(long i=0; i<10000000000l; i++) {
    if(flag1 & flag2) {
        System.out.println("");
    }
}

long end = System.currentTimeMillis();
System.out.println("Execution time" + (end - start)  + "ms");

& Is used in the conditional expression for if.

inspection result

I actually ran the above two types of programs and took statistics on the execution time of each program. The table below shows the results.

Program execution time (unit: ms)
With short-circuit evaluation(&&) No short-circuit evaluation(&)
1st time 3546 3500
Second time 3556 3595
3rd time 3586 3565
4th time 3574 3564
5th time 3552 3636
6th time 3570 3620
7th time 3512 3568
8th time 3563 3597
9th time 3560 3565
10th time 3555 3500
average 3557.6 3571.0

As far as the average of the table is seen, it is considered that the processing speed is faster when the short-circuit evaluation is performed. However, in this experiment, the number of samples was small, and the difference in execution time between with and without short-circuit evaluation was small, so processing is faster using && with short-circuit evaluation than & without short-circuit evaluation. It is a little weak to conclude that it will be.

Summary

In the experiment I conducted this time, I got the result that the processing is faster when using the short-circuit evaluation. For the time being, it is better to use && when taking the logical product of multiple boolean values in Java. Also, in other languages such as C, & may have a completely different function of taking both sides as binary numbers and ANDing each digit, so mistakes occur when switching languages. It is recommended to use && if you can get the same result by using & and && in Java to prevent it from increasing.

Recommended Posts

Is short-circuit evaluation really fast? Difference between && and & in Java
Difference between int and Integer in Java
Difference between next () and nextLine () in Java Scanner
[Java] Difference between == and equals
[Java] Difference between static final and final in member variables
[JAVA] What is the difference between interface and abstract? ?? ??
What is the difference between Java EE and Jakarta EE?
[Java] Difference between equals and == in a character string that is a reference type
[Java] Difference between Hashmap and HashTable
Jersey --What is Difference Between bind and bindAsContract in HK2?
[Java] Difference between array and ArrayList
[Java] Difference between Closeable and AutoCloseable
[Java] Difference between StringBuffer and StringBuilder
[Java] Difference between length, length () and size ()
[Java] What is the difference between form, entity and dto? [Bean]
Difference between pop () and peek () in stack
[For beginners] Difference between Java and Kotlin
Difference between getText () and getAttribute () in Selenium
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
Arrylist and linked list difference in java
Difference between EMPTY_ELEMENTDATA and DEFAULTCAPACITY_EMPTY_ELEMENTDATA in ArrayList
[Java] Difference between Intstream range and rangeClosed
Understand the difference between int and Integer and BigInteger in java and float and double
[Java] Understand the difference between List and Set
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
Distinguish between positive and negative numbers in Java
[Java] Difference between "final variable" and "immutable object"
Difference between vh and%
Difference between i ++ and ++ i
What is the difference between a class and a struct? ?? ??
What is the difference between System Spec and Feature Spec?
About the difference between classes and instances in Ruby
Difference between new and create in Rais action controller
[Rails] What is the difference between redirect and render?
What is the difference between skip and pending? [RSpec]
[Java beginner] Difference between length and length () ~ I don't know ~
What is the difference between the responsibilities of the domain layer and the application layer in the onion architecture [DDD]
Difference between product and variant
Difference between redirect_to and render
[Rails] What is the difference between bundle install and bundle update?
Rails: Difference between resources and resources
Difference between Java and JavaScript (how to find the average)
Difference between puts and print
Difference between redirect_to and render
Difference between CUI and GUI
Difference between variables and instance variables
Difference between mockito-core and mockito-all
Difference between element 0, null and empty string (check in list)
[Java] Difference between assignment of basic type variable and assignment of reference type variable
Difference between class and instance
Difference between bundle and bundle install
What is the difference between an action and an instance method?
[Java] Check the difference between orElse and orElseGet with IntStream
Difference between ArrayList and LinkedList
Difference between render and redirect_to
StringUtils.isNotBlank is convenient for empty judgment and null judgment in java
Think about the differences between functions and methods (in Java)
Difference between List and ArrayList
java Generics T and? Difference
Now in the third year, the misunderstanding that I noticed is the difference between the equals method and ==
Differences in how to handle strings between Java and Perl