Skip to content

Instantly share code, notes, and snippets.

@rrfaria
Last active September 29, 2024 16:05
Show Gist options
  • Select an option

  • Save rrfaria/2c64d5f9ade0440c82efdd9d2d4c5a90 to your computer and use it in GitHub Desktop.

Select an option

Save rrfaria/2c64d5f9ade0440c82efdd9d2d4c5a90 to your computer and use it in GitHub Desktop.
Analyse Object Literal vs Switch case
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`);
@rrfaria
Copy link
Author

rrfaria commented Sep 29, 2024

image

Now just using console.time to analyse speed

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";
}

const severity = 3; 

console.time("Switch Case");
for (let i = 0; i < 1000000; i++) {
    getLabelSwitch(severity);
}
console.timeEnd("Switch Case");

console.time("Object Literal");
for (let i = 0; i < 1000000; i++) {
    getLabelObjectLiteral(severity);
}
console.timeEnd("Object Literal");

image

@rrfaria
Copy link
Author

rrfaria commented Sep 29, 2024

And now a fair comparison:
Just moving console.time to a function look at difference and it is all because the way js executes
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment