Let's assume I have to check three different cases. Is it better to use if/else or switch?
- 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(); |