Last active
September 29, 2024 16:05
-
-
Save rrfaria/2c64d5f9ade0440c82efdd9d2d4c5a90 to your computer and use it in GitHub Desktop.
Analyse Object Literal vs Switch case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getLabelSwitch(severity) { | |
| switch (severity) { | |
| case 1: | |
| return "Error"; | |
| case 2: | |
| return "Warning"; | |
| case 3: | |
| return "Information"; | |
| case 4: | |
| return "Hint"; | |
| default: | |
| return "Diagnostic"; | |
| } | |
| } | |
| const severityLabels = { | |
| 1: "Error", | |
| 2: "Warning", | |
| 3: "Information", | |
| 4: "Hint" | |
| }; | |
| function getLabelObjectLiteral(severity) { | |
| return severityLabels[severity] || "Diagnostic"; | |
| } | |
| function measurePerformance(fn, severity, iterations = 1000000) { | |
| const start = performance.now(); | |
| for (let i = 0; i < iterations; i++) { | |
| fn(severity); | |
| } | |
| const end = performance.now(); | |
| return end - start; | |
| } | |
| const severity = 3; | |
| const switchTime = measurePerformance(getLabelSwitch, severity); | |
| const objectLiteralTime = measurePerformance(getLabelObjectLiteral, severity); | |
| console.log(`Switch Case: ${switchTime} ms`); | |
| console.log(`Object Literal: ${objectLiteralTime} ms`); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And now a fair comparison:

Just moving console.time to a function look at difference and it is all because the way js executes