var reportsArr = [{
id: `john`,
text: `one`
}, {
id: `jane`,
text: `two`
}, {
id: `bob`,
text: `three`
}]
var reportsObj = {
['john']: {
text: `one`
},
[`jane`]: {
text: `two`
},
[`bob`]: {
text: `three`
}
}
var i = 0,
count = 1000,
jane;
for (i = 0; i < count; i++) {
janeIndex = reportsArr.findIndex(el => el.id === 'jane');
}
for (i = 0; i < count; i++) {
janeIndex = reportsObj['jane'];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array lookup | |
Obj lookuo |
Test name | Executions per second |
---|---|
Array lookup | 8520.1 Ops/sec |
Obj lookuo | 21190.8 Ops/sec |
Let's break down the provided JSON benchmark and explain what is being tested, compared, and other considerations.
Benchmark Definition
The benchmark definition is represented by two test cases:
for
loop to iterate count
number of times (1000). Inside the loop, it finds the index of an element in the reportsArr
array that matches the string 'jane'
. The code janeIndex = reportsArr.findIndex(el => el.id === 'jane');
is used for this purpose.for
loop to iterate count
number of times (1000). Inside the loop, it finds the value associated with the key 'jane'
in the reportsObj
object using the syntax reportsObj['jane']
.Comparison
The two test cases are compared in terms of execution time. The one that executes faster will be reported as the winner.
Pros and Cons
findIndex
, have optimized implementations.reportsObj['jane']
).Library/Function
There is no specific library mentioned in the benchmark definition. However, findIndex
is a built-in JavaScript method used in both test cases.
Special JS Feature/Syntax
The benchmark uses the following special syntax:
template literals
: The string concatenation in the Script Preparation Code
, specifically: "var reportsArr = [...]; var reportsObj = {...};"
. This syntax allows for more readable and efficient string construction.el => el.id === 'jane'
in the array lookup test case. Arrow functions provide a concise way to define small, single-expression functions.Alternatives
Other alternatives could include:
Map
or Set
, which might offer different performance characteristics.Keep in mind that the optimal approach depends on the specific use case, dataset size, and performance requirements.