Skip to content

Instantly share code, notes, and snippets.

@jalal246
Created October 11, 2019 15:56
Show Gist options
  • Select an option

  • Save jalal246/513c1fad62ab4138c4cb39637199496e to your computer and use it in GitHub Desktop.

Select an option

Save jalal246/513c1fad62ab4138c4cb39637199496e to your computer and use it in GitHub Desktop.
JavaScript Performance Test: if/else VS switch

Motivation

Let's assume I have to check three different cases. Is it better to use if/else or switch?

Conclusion

  • switch took: 21.1999999883119 ms
  • if/else took: 14.66499999514781 ms

Seems like if/else is always a better choice for sake of performance.

/**
* Utility, generates random number.
*/
function randNumber() {
return Math.ceil(Math.random() * 10);
}
/**
* Utility, generates random number between 1 and 3.
*/
function diceWithMaxThee() {
return Math.floor(Math.random() * 3) + 1;
}
function testSwitch(direction, x1, x2, y1, y2) {
let isQualified;
switch (direction) {
case "up":
isQualified = x1 > x2 && y1 > y2;
case "down":
isQualified = x1 < x2 && y1 < y2;
default:
isQualified = x1 < x2 || y1 < y2;
}
return isQualified;
}
function testIfELse(isUp, isDown, x1, x2, y1, y2) {
let isQualified;
if (isUp) {
isQualified = x1 > x2 && y1 > y2;
} else if (isDown) {
isQualified = x1 < x2 && y1 < y2;
} else {
isQualified = x1 < x2 || y1 < y2;
}
return isQualified;
}
const MAX_LOOP = 10000;
function runTest() {
let perf;
perf = performance.now();
for (let i = 0; i < MAX_LOOP; i++) {
const x1 = randNumber();
const x2 = randNumber();
const y1 = randNumber();
const y2 = randNumber();
const result = diceWithMaxThee();
let direction;
if (result === 1) {
direction = "up";
} else if (result === 2) {
direction = "down";
}
testSwitch(direction, x1, x2, y1, y2);
}
console.log(`switch took: ${performance.now() - perf} ms`);
perf = performance.now();
for (let i = 0; i < MAX_LOOP; i++) {
const x1 = randNumber();
const x2 = randNumber();
const y1 = randNumber();
const y2 = randNumber();
const result = diceWithMaxThee();
let isUp = false;
let isDown = false;
if (result === 1) {
isUp = true;
} else if (result === 2) {
isDown = true;
}
testIfELse(isUp, isDown, x1, x2, y1, y2);
}
console.log(`if/else took: ${performance.now() - perf} ms`);
}
runTest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment