count leading zeros (v2)

Revision 2 of this benchmark created by Mathieu 'p01' Henri 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;
    }
    
    var lead3 = function(i)
    {
    var o=32,i=i|0,s=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4];
    if(i<0)return 32;
    if(i&0xffff0000)i>>=16,o-=16;
    if(i&0x0000ff00)i>>=8,o-=8;
    if(i&0x000000f0)i>>=4,o-=4;
    return o-s[i];
    };

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.