2

I was curious about boolean optimizations, so I made a small program to test these equivalent expressions:

(A && B) || (!A && !B)

!(A ^ B)

Here is the program on Ideone: https://ideone.com/cr3guM

I expected the shorter expression to be slightly faster, but according to my tests, whichever one runs first is always the fastest. Even if I run them back to back, or alternate between the tests, the first one is always fastest, and so are future executions of that same method.

Example:

timeLongForm();  // 879ms
timeShortForm(); // 1316ms
timeLongForm();  // 876ms

swapped order:

timeShortForm(); // 917ms
timeLongForm();  // 1375ms
timeShortForm();  // 915ms

What is causing this?

BLuFeNiX
  • 2,496
  • 2
  • 20
  • 40
  • How many times did you try this? It *could* just be a coincidence. – RaminS Apr 07 '16 at 17:51
  • @Gendarme dozens of times, so I think that is unlikely :) – BLuFeNiX Apr 07 '16 at 17:53
  • 2
    The JIT compiler likely completely removes the `answer` variables and the assignment, because they are effectively noops. Retry your test with a proper benchmarking framework like JMH. – Clashsoft Apr 07 '16 at 17:57
  • 1
    Interestingly, the middle function still takes longer with or without the loop bodies https://ideone.com/OcA0EQ – flakes Apr 07 '16 at 18:04
  • @flkes Hmm, well that seems to support Clashsoft's assertion. – BLuFeNiX Apr 07 '16 at 18:11
  • 1
    This might be a victim of [branch prediction](http://stackoverflow.com/a/11227902). –  Jan 01 '17 at 06:49

0 Answers0