Skip to content

Instantly share code, notes, and snippets.

@Antnee
Last active August 24, 2020 14:50
Show Gist options
  • Save Antnee/dd8f0e6d8cd108c15a8c943b5b9231fc to your computer and use it in GitHub Desktop.
Save Antnee/dd8f0e6d8cd108c15a8c943b5b9231fc to your computer and use it in GitHub Desktop.
What is quicker to check if a number is even or not? Checking the bits, or performing a modulus operation?
<?php
/**
* Check if a number is even by examining the bit for 1 (ie the odd number 'flag')
*/
function isEvenBit(int $num): bool
{
return !($num & 0b1);
}
/**
* Check if a number is even by examining if the remainder of an n mod 2 calculation is zero
*/
function isEvenMod(int $num): bool
{
return ($num % 2) === 0;
}
$start = microtime(true);
for ($i=0; $i<1000000000; $i++) {
isEvenBit($i);
}
echo "\nBit check ran in " . (microtime(true) - $start) . "seconds\n";
$start = microtime(true);
for ($i=0; $i<1000000000; $i++) {
isEvenMod($i);
}
echo "\nModulo check ran in " . (microtime(true) - $start) . "seconds\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment