Category Archives: Performance

How to programmatically check if a Number is even: Multiple solutions

There are multiple ways to check if a number is even. Most people are using the Modulo Operator:

return (number % 2 == 0);

The modulo operator divides the number and returns the rest of the division. If we divide by 2 and the rest is 0, it’s obviously an even number. Now, the modulo operator is not very fast. In most languages we could also use this little trick:

return ((number / 2) * 2 == number);

If ‘number’ was, let’s say, 13, dividing by 2 would result in 6.5. Since it’s an integer, the .5 just gets cut off, leaving us a 6 behind. Multiplying 6 by 2 results in 12. 12 is not equal to the original number (13), therefore it returns false (number is odd).

That’s a lot faster than using the modulo operator. But we can do this even faster by using the Bitwise AND-Operator:

return !(number & 1);

With this operator, we can mask a number with bits and perform a bitwise AND operation. Lets take 13 again for an example. 13 in binary is this:

1101

The first bit represents 2^0. Every odd number has that bit set, so if we mask 13 with 1 we get this:

  1101
& 0001
  ____
  0001

If we would mask an even number like 12 with 1, we get this:

  1100
& 0001
  ____
  0000

Therefore, the output of (number & 1) is true if it’s odd. With the NOT-Operator we simply invert the boolean value and get a very fast isEven method. Here are some benchmarks in JavaScript (The last function does not work in JS, since it’s an implicit language):

Function Execution Time
isEvenBitwise 9.5016
isEvenModulo 37.2635
isEvenIntegerTrick 12.0399

(Firefox 20.0, Windows 7, 1e6 iterations)

Conclusion

In most cases, it doesn’t matter what method you are using. If you need speed, use the bitwise AND-operator. If you need readability, use the modulo operator.