Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Switch vs Object Literal v2
(version: 0)
Comparing performance of:
Switch vs Object Literal
Created:
4 years ago
by:
Guest
Jump to the latest result
Script Preparation code:
var str = 'abc'; str = str.charAt(Math.floor(Math.random() * 3)); function a() { console.log('A'); } function b() { console.log('B'); } function c() { console.log('C'); }
Tests:
Switch
switch (str) { case 'a': a(); break; case 'b': b(); break; case 'c': b(); break; }
Object Literal
var objLiteral = { a: a, b: b, c: c } objLiteral[str]();
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
Switch
Object Literal
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
gemma2:9b
, generated one year ago):
This benchmark tests the performance of two different approaches for selecting code to execute based on a string value: **1. `switch` statement:** * **Definition:** The `switch` statement evaluates an expression and executes the block of code associated with the matching case. * **Code:** ```javascript switch (str) { case 'a': a(); break; case 'b': b(); break; case 'c': b(); break; } ``` * **Pros:** Often considered the most readable and intuitive way to handle multiple conditional checks. Can be efficient for matching against known values. **2. Object Literal:** * **Definition:** An object literal associates string keys with function values. The code then looks up the function corresponding to the string value and calls it. * **Code:** ```javascript var objLiteral = { a: a, b: b, c: c }; objLiteral[str](); ``` * **Pros:** Can be more flexible for handling a larger number of cases, especially if the mapping between values and functions is dynamic. **Cons/Considerations:** * **Switch Statements:** Can become inefficient with a large number of cases due to branch prediction overhead. Requires explicit `break` statements to prevent "fallthrough" to subsequent cases. * **Object Literals:** Can be less readable than `switch` for simple mappings. More memory intensive due to the creation of the object literal. **Alternatives:** * **Map:** A more dynamic and efficient alternative to object literals, especially when dealing with a large number of key-value pairs. Let me know if you have any more questions about this benchmark or JavaScript performance optimization!
Related benchmarks:
Switch vs Object Literal defined once
Switch vs Object Literal larger
Switch vs Object Literal - testing with stable input
Switch vs Object Literal (fixed prep code)
Switch vs Object Literal 24r34rf3rr
Comments
Confirm delete:
Do you really want to delete benchmark?