Performance counts - Should you use bitwise or modulus when deciding odd/even rows
Using a bitwise operator is faster than using modulus operators, right? Apparently this is not the case with PHP.
This is a common method of checking for odd and even numbers:
$result= ( $i % 2 ) ? $odd : $even;Using bitwise operators like so:
$result= ( ( $i & 1 ) == 0 ) ? $odd : $even;should be faster, but it's actually a fair bit slower. Permalink for this article http://mirror.magicode.org/content/PHP_operators_odd_and_even_performance_counts
Running a loop from 0 to 1000000 (million) gives the following result:
modulus: 10000000 calcs of $i % 2 generated in: 6.5786 seconds modulus: 10000000 calcs of $i % 2 $a generated in: 6.9860 seconds modulus: 10000000 calcs of $i % 2 $a generated in: 6.3890 seconds ternary: 10000000 calcs of $i & 1 == 0 $a generated in: 7.1081 seconds ternary: 10000000 calcs of $i & 1 == 0 $a generated in: 7.0160 seconds ternary: 10000000 calcs of $i & 1 == 0 $a generated in: 7.0735 secondsThis text was originally written for http://blog.magicode.org
So, there you go folks. Keep using those $i%2 for checking for odd/even. :) If you see this notice on any site other than magicode.org, it's probably been lifted without consent
PS! You can download the script and see the results for yourself.
