var array = [];
var elements = 10000;
for (var i = 0; i < elements; i++) {
array.push({
index: i
});
}
var arrayObject = {};
array.forEach(element => {
arrayObject[element.index] = element;
});
let randomIndex = (Math.random() * (elements - 1)) | 0
let foundElement = array.find(element => element.index === randomIndex);
let randomIndex = (Math.random() * (elements - 1)) | 0
let foundElement = arrayObject[randomIndex];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.find | |
Object |
Test name | Executions per second |
---|---|
Array.find | 72661.3 Ops/sec |
Object | 3006971.0 Ops/sec |
Let's break down the provided JSON and explain what is tested on that benchmark.
The test case measures the performance difference between two approaches: using Array.prototype.find()
and accessing an object by index.
Options Compared
There are two options being compared:
arrayObject[randomIndex]
: This approach accesses the desired element in the arrayObject
object by its index. It's a simple and straightforward way to get an element.
array.find(element => element.index === randomIndex)
: This approach uses the Array.prototype.find()
method, which returns the first element in the array that satisfies the provided condition. In this case, it finds an element with an index matching randomIndex
.
Pros and Cons
arrayObject[randomIndex]
:array.find()
:Library/Script Used
The script uses Array.prototype.find()
which is a part of JavaScript's standard library. The forEach()
method also used in the initial setup code, is another standard JavaScript method that iterates over an array or object.
Special JS Feature/Syntax
There is no special feature or syntax being tested here. It's purely about comparing two simple algorithmic approaches in a controlled environment.
Other Alternatives
If you needed to measure performance difference between other methods (e.g., array.indexOf()
), you could consider adding more test cases, such as:
array.indexOf(randomIndex)
for...of
loopHowever, keep in mind that each additional test case will add complexity and potentially skew the results.