Getting bit length of a number (v2)

Revision 2 of this benchmark created on


Setup

function getBitLengthShifting(num) {
    let length = 0;
    
    if (num >= 1 << 16) { 
        num >>= 16; 
        length += 16;
    }
    if (num >= 1 << 8) { 
        num >>= 8; 
        length += 8;
    }
    if (num >= 1 << 4) { 
        num >>= 4; 
        length += 4;
    }
    if (num >= 1 << 2) { 
        num >>= 2; 
        length += 2;
    }
    if (num >= 1 << 1) { 
        length += 1;
    }

    return length + 1; // Add 1 to account for the last bit
}

function getBitLengthLooping(num) {
    if (num === 0) return 1; // Special case: 0 is represented by a single bit "0"
    
    let length = 0;
    while (num > 0) {
        num >>= 1; // Shift the number right by 1 bit
        length++;
    }
    return length;
}

function getBitLengthMath(num) {
    if (num === 0) return 1; // Special case: 0 is represented by a single bit "0"
    return Math.floor(Math.log2(num)) + 1;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Shifting
for(let i = 0; i < 10_000; ++i) {
	getBitLengthShifting(i);
}
ready
Loop
for(let i = 0; i < 10_000; ++i) {
	getBitLengthLooping(i);
}
ready
Math function
for(let i = 0; i < 10_000; ++i) {
	getBitLengthMath(i);
}
ready

Revisions

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