Loop vs If condition

Benchmark created on


Setup

var keyCode = 100;
var keyCodeRanges = [
                [48, 57],    // 0-9
                [65, 90],    // a-z
                [96, 107],   // Numpad0-Numpad9(96-105), NumpadMultiply(106), NumpadAdd(107)
                [109, 111],  // NumpadSubtract(109), NumpadDecimal(110), NumpadDivide(111)
                [186, 192],  // ;=,-./
                [219, 222]   // [\|]'
            ];

Test runner

Ready to run.

Testing in
TestOps/sec
If condition
 var isAlphaNumericOrSpecialKey = (keyCode >= 48 && keyCode <= 57) // 0-9
            || (keyCode >= 65 && keyCode <= 90) // a-z
            || (keyCode >= 186 && keyCode <= 192) // ;=,-./`
            || (keyCode >= 219 && keyCode <= 222);
            
            if (isAlphaNumericOrSpecialKey) {
            	console.log('Hello');
            }
ready
Loop
var isAlphaNumericOrSpecialKey = false;
            for (var i = 0, j = keyCodeRanges.length; i < j; i++) {
                // Loop through all the ranges to find the keyCode pressed
                var keyCodeRange = keyCodeRanges[i];
                isAlphaNumericOrSpecialKey = keyCode >= keyCodeRange[0] && keyCode <= keyCodeRange[1];
                if (isAlphaNumericOrSpecialKey) {
                    console.log('Hello');
                }
            }
ready

Revisions

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