Faster Java boolean inversions with XOR

05 Jan 2006

Allan Caplan has come up with a new PMD optimization rule - this one finds places where booleans are being inverted like this:

x = !x; // slow
x = x ? false : true; // slow

The above code works, but using XOR is about twice as fast:

x ^= true; // fast!

Original credit for this discovery goes to Dr Heinz Kabutz; he did a nice writeup on this. Note that the writeup doesn't include the XOR bytecode; here it is:

   0:   iconst_1
   1:   istore_1
   2:   iload_1
   3:   iconst_1
   4:   ixor
   5:   istore_1
   6:   return

It's several instructions smaller than the other methods, so the class file gets four bytes smaller, too!

Thanks again to Allan for putting together a nice patch with this rule - he even included complete unit tests! Excellent work, Allan!

Updated: Fixed example of the right way to do it; thanks to Leslie Hensley for the catch!

Support PMD, get the book!