count leading zeros (v3)

Revision 3 of this benchmark created by Devon Govett on


Setup

function lead(m) {
      var c, i;
      c = 1 << 31;
      for (i = 0; i < 32; i += 1) {
        if ((c & m) !== 0) return i;
        c >>>= 1;
      }
      return 32;
    }
    
    function lead2(input) {
        var output = 0,
            curbyte = 0;
            
        while(1) { // emulate goto in JS using the break statement :D
            curbyte = input >>> 24;
            if (curbyte) break;
            output += 8;
            
            curbyte = input >>> 16;
            if (curbyte & 0xff) break;
            output += 8;
            
            curbyte = input >> 8;
            if (curbyte & 0xff) break;
            output += 8;
            
            curbyte = input;
            if (curbyte & 0xff) break;
            output += 8;
            
            return output;
        }
        
        if (!(curbyte & 0xf0))
            output += 4;
        else
            curbyte >>>= 4;
            
        if (curbyte & 0x8)
            return output;
        if (curbyte & 0x4)
            return output + 1;
        if (curbyte & 0x2)
            return output + 2;
        if (curbyte & 0x1)
            return output + 3;
    
        /* shouldn't get here: */
        return output + 4;
    }
    
    function lead3(x) {
        return 32 - (x).toString(2).length;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
lead
lead(21);
lead(7);
lead(3);
lead(10);
ready
lead2
lead2(21);
lead2(7);
lead2(3);
lead2(10);
ready
lead3
lead3(21);
lead3(7);
lead3(3);
lead3(10);
ready

Revisions

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