Search code examples
javabooleanxor

What is the quickest way to flip a Java boolean?


Which way is quicker and less resource intensive:

boolean = !boolean
boolean ^= boolean

Edit: This is not an opinion based question. There IS a correct answer.


Solution

  • I measured with the following code.

    public static void main(String[] args)
    {
    
        boolean myVariable = true;
        long startTime = 0;
        long endTime = 0;
        long duration1 = 0;
        long duration2 = 0;
    
    
        for(int i=0; i<1000; i++) {
            startTime = System.nanoTime();
            myVariable = !myVariable;
            endTime = System.nanoTime();
    
            duration1 += (endTime - startTime);
    
    
            startTime = System.nanoTime();
            myVariable ^= myVariable;
            endTime = System.nanoTime();
    
            duration2 += (endTime - startTime);
    
        }
    
            System.out.println("The duration for the first operation is :" + (duration1/1000));
            System.out.println("The duration for second operation is :" + (duration2/1000));
    }
    

    and the results are (in nanoseconds)

    The duration for the first operation is :140

    The duration for the second operation is :123

    Based on this analysis, the boolean ^= boolean is quicker than the boolean = !boolean.