Last active
February 24, 2016 02:01
-
-
Save iSkore/0d307079931cdc8685d6 to your computer and use it in GitHub Desktop.
Speed test on power of two
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unit test on "is power of two?" check