Another approach is to run a micro benchmark and analyse the time taken by each variants. Here are the results:
Benchmark Mean Units Time vs. baseline
baseline 10.330 nsec/op 0.000
bitAnd 12.075 nsec/op 1.745
bitShift 12.309 nsec/op 1.979
modulo 12.309 nsec/op 4.529
(the baseline is a method that just returns i == 0
)
Conclusion:
i & 1
-----> takes about 1.75ns
i << 31
--> takes about 2.00ns
i % 2
-----> takes about 4.50ns
In other words, i % 2
is 2x slower than i & 1
.
Notes: benchmark done with jmh. The baseline is high because I generate random numbers to make sure the method are not optimised away. Tests run on an i7 @ 2.8GHz (i.e. one cycle = 0.35ns) with hotspot 7.