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 = 10000,
jane;
for (i = 0; i < count; i++) {
janeIndex = reportsArr.findIndex(el => el.id === 'jane');
jane = reportsArr[janeIndex]
}
for (i = 0; i < count; i++) {
jane = reportsObj['jane'];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.findIndex lookup | |
Obj lookup |
Test name | Executions per second |
---|---|
Array.findIndex lookup | 285.1 Ops/sec |
Obj lookup | 739.7 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition Json
The JSON represents a JavaScript microbenchmark named "Object vs Array.findIndex lookups". The benchmark has two test cases:
The script preparation code initializes two arrays, reportsArr
and reportsObj
, which contain similar data but in different formats (arrays vs objects). The i
variable is initialized to 0, and the count variable is set to 10000.
Options Compared
The benchmark compares two approaches:
findIndex()
method on an array to find the index of a specific element.[]
) to get a value.Pros and Cons
Pros:
[]
) to access properties.Cons:
reportsArr[janeIndex]
).Pros:
[]
) or indexing (reportsObj['jane']
).Cons:
findIndex()
for large arrays, as it uses a linear search algorithm.[]
).Library and Purpose
In the script preparation code, the library used is not explicitly mentioned. However, based on the context, it appears that the benchmark assumes the use of JavaScript's built-in findIndex()
method, which does not require any external libraries.
Special JS Feature or Syntax
No special JS feature or syntax is used in this benchmark. It only uses standard JavaScript syntax and features.
Other Alternatives
If you wanted to rewrite these tests using alternative approaches, here are a few options:
findIndex()
, you could use the indexOf()
method on the array, which is similar but does not have the same benefits for large arrays.object.keys()
and then iterate over the resulting array using Array.prototype.forEach()
to get a value.[]
).However, these alternatives would likely not be as efficient or readable as the original findIndex()
and object lookup approaches.