count the on bits

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function bitCount(num) {
      var onBits = 0;
      var maxPowerOfTwo = 1;
   
      while (num > 0) {
        while (maxPowerOfTwo << 1 <= num) {
          maxPowerOfTwo = maxPowerOfTwo << 1;
        }
        num = num - maxPowerOfTwo;
        maxPowerOfTwo = 1;
        onBits += 1;
      }
   
      return onBits;
    }
   
    function cheatBitCount(num) {
      var binString = num.toString(2);
      var onBits = 0;
   
      for (var i = 0; i < binString.length; i++) {
        if (binString[i] === '1') {
          onBits += 1;
        }
      }
      return onBits;
    }
   
    var arr = [1,2,3,4,5,6,7,8,19, 230, 25555];
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
not cheating
for (x in arr) {
  bitCount(arr[x]);
}
 
pending…
cheating
for (x in arr) {
  cheatBitCount(arr[x]);
}
 
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment