var str = 'abc';
str = str.charAt(Math.floor(Math.random() * 3));
const useSwitch = (str) => {
switch (str) {
case 'a': return 'A'; break
case 'b': return 'B'; break
case 'c': return 'C'; break
}
}
console.log(useSwitch(str));
const useObject = (str) => {
let letters = {
a: 'A',
b: 'B',
c: 'C'
}
return letters[str]
}
console.log(useObject(str));
var arrow = {
a: () => 'A',
b: () => 'B',
c: () => 'C'
}
console.log(arrow[str]());
var objLiteral = {
a: function() {
console.log('A');
},
b: function() {
console.log('B');
},
c: function() {
console.log('C');
}
}
objLiteral[str]();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Object property | |
Object with arrow funcion | |
Object with funcion (from the link in description) |
Test name | Executions per second |
---|---|
Switch | 59416.1 Ops/sec |
Object property | 58909.7 Ops/sec |
Object with arrow funcion | 55503.1 Ops/sec |
Object with funcion (from the link in description) | 57313.0 Ops/sec |
Let's break down the provided benchmark JSON and explain what's being tested, compared, and discussed.
Benchmark Purpose: The benchmark compares four approaches to access a value stored in an array or object:
switch
statementstr['a']
, etc.)arrow[str]()
)objLiteral[str]()
)The benchmark aims to evaluate the performance of these four approaches on a JavaScript engine.
Comparison Options: The benchmark compares the execution speed of each approach using various browsers and devices, including Chrome Mobile 79 running on Android 9. The comparison options are:
Pros and Cons:
Library Usage:
None of the benchmark test cases use external libraries. The useSwitch
and objLiteral
functions rely on built-in JavaScript features, while useObject
uses an object literal with bracket notation to access the property.
Special JS Features or Syntax: None of the test cases use special JavaScript features like ES6 modules, async/await, or Promises. The focus is on evaluating the performance of basic syntax elements.
Alternatives: If you're interested in exploring alternative approaches, here are some options:
By analyzing the benchmark's structure and comparison options, you can gain insights into the performance characteristics of each approach and make informed decisions about which syntax to use in your own JavaScript applications.