var objLiteral = {
0: function() {
console.log('A');
},
1: function() {
console.log('B');
},
2: function() {
console.log('C');
}
}
var arrayLiteral = [
function() {
console.log('A');
},
function() {
console.log('B');
},
function() {
console.log('C');
}
];
function usingSwitch(c) {
switch (c) {
case 0: console.log('A'); break;
case 1: console.log('B'); break;
case 2: console.log('C'); break;
}
}
usingSwitch(Math.floor(Math.random() * 3))
objLiteral[Math.floor(Math.random() * 3)]();
arrayLiteral[Math.floor(Math.random() * 3)]();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Object Literal | |
Array Literal |
Test name | Executions per second |
---|---|
Switch | 51493.5 Ops/sec |
Object Literal | 111453.7 Ops/sec |
Array Literal | 103886.2 Ops/sec |
Let's dive into the provided JSON and explore what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is comparing three approaches to call functions with different syntax:
usingSwitch(Math.floor(Math.random() * 3))
objLiteral[Math.floor(Math.random() * 3)]();
arrayLiteral[Math.floor(Math.random() * 3)]();
Library and Purpose
The benchmark uses two libraries:
console.log
: a built-in function in JavaScript that outputs the specified value to the console.Math.random()
: a built-in function in JavaScript that generates a random number between 0 (inclusive) and 1 (exclusive).Special JS Feature/Syntax
The benchmark uses the switch
statement, which is a control structure that allows execution of code blocks based on conditions. In this case, it's used to call functions with different syntax.
Now, let's compare the three approaches:
Switch Statement
Pros:
Cons:
case
statements, making the code harder to read and maintainObject Literal
Pros:
objLiteral[0]()
)Cons:
Array Literal
Pros:
arrayLiteral[0]()
)Cons:
Other Considerations
Now that we've explored the different approaches, let's look at the benchmark results:
The current benchmark result shows that Object Literal has a higher execution speed (381604.90625 executions/second) compared to Switch Statement (373330.875 executions/second) and Array Literal (367839.1875 executions/second).
Keep in mind that these results may vary depending on the specific use case, JavaScript engine, and hardware.
As an alternative to this benchmark, you could consider using a different approach, such as:
switch
or object/literal notation, use function pointers (e.g., function* foo() { ... }
) to call functions.These alternatives may offer different trade-offs in terms of readability, maintainability, and performance.