var str = 'abc';
str = str.charAt(Math.floor(Math.random() * 3));
switch (str) {
case 'a': console.log('A'); break;
case 'b': console.log('B'); break;
case 'c': console.log('C');
}
var objLiteral = {
a: 'A',
b: 'B',
c: 'C'
}
console.log(objLiteral[str]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Object Literal |
Test name | Executions per second |
---|---|
Switch | 36041.1 Ops/sec |
Object Literal | 35079.8 Ops/sec |
Let's dive into the explanation of the provided JSON benchmark.
Benchmark Overview
The benchmark compares the performance of two approaches to access an element in an object or string: using a switch
statement and using an object literal with bracket notation (objLiteral[str]
). The benchmark is designed to test which approach is faster on modern browsers, specifically Chrome 67 on Linux desktop platforms.
Script Preparation Code
The script preparation code sets up the initial state of the variables involved in the benchmark:
var str = 'abc';
str = str.charAt(Math.floor(Math.random() * 3));
Here, a random character is randomly selected from the string 'abc'
and stored in the str
variable. This ensures that the test results are not dependent on a specific input value.
Benchmark Definition
The benchmark definition specifies two test cases:
switch
statement to access the character at index 0 of the string.switch (str) {
case 'a': console.log('A'); break;
case 'b': console.log('B'); break;
case 'c': console.log('C');
}
This approach uses a switch statement with three cases, one for each character in the string.
var objLiteral = {
a: 'A',
b: 'B',
c: 'C'
}
console.log(objLiteral[str]);
This approach creates an object literal with three properties, one for each character in the string, and then uses bracket notation to access the value associated with the randomly selected index.
Pros and Cons of Each Approach
Library Used
The benchmark does not explicitly use any external libraries. The console.log
function is part of the built-in JavaScript API, and the object literal creation and bracket notation are standard JavaScript syntax.
Special JS Features
There are no special JavaScript features used in this benchmark beyond the standard syntax for object literals and switch statements.
Alternative Approaches
Other approaches to access an element in an object or string include:
arr[str]
.String.match()
or String.test()
, e.g., /abc/.exec(str)[0]
.get()
method to access the element at index 0, e.g., var map = new Map(); map.set('a', 'A'); map.get(str)
.