Skip to content

Instantly share code, notes, and snippets.

@iSkore
Last active February 24, 2016 02:01
Show Gist options
  • Save iSkore/0d307079931cdc8685d6 to your computer and use it in GitHub Desktop.
Save iSkore/0d307079931cdc8685d6 to your computer and use it in GitHub Desktop.
Speed test on power of two
// TEST A
function isPowerA ( x ) {
while ( ( ( x % 2 ) === 0 ) && x > 1 ) x /= 2;
return ( x === 1 );
}
var i = 10000000;
while ( i > 0 ) {
isPowerA( 2048 );
i--;
}
// result: Approx 218 ms
// TEST B
function isPowerB ( x ) {
return ( x && !( x & ( x - 1 ) ) );
}
var i = 10000000;
while ( i > 0 ) {
isPowerB( 2048 );
i--;
}
// result: Approx 66 ms
// TEST C
function isPowerC ( x ) {
return ( ( x & ~15 ) === x );
}
var i = 10000000;
while ( i > 0 ) {
isPowerC( 2048 );
i--;
}
// result: Approx: 68 ms
@iSkore
Copy link
Author

iSkore commented Feb 24, 2016

Unit test on "is power of two?" check

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment