function randstr(N) {
return (Math.random().toString(36)+'00000000000000000').slice(2, N+2);
}
var dataset = [];
for (var x = 0; x < 100000; x++) {
dataset.push({id: 'xx' + x, name: randstr(10), other: randstr(10)});
}
var indexedDataset = {};
for (var item of dataset) {
indexedDataset[item.id] = item;
}
var indexMap = {};
for (var [i, item] of dataset.entries()) {
indexMap[item.id] = i;
}
function assertEq(a, b) {
if (a !== b) {
new Error(`Failed assert: "${a}" expected "${b}"`);
}
}
for (var x = 0; x < 10000; ++x) {
const item = dataset.find(v => v.id == 'xx' + 123);
assertEq(item.id, 'xx' + 123);
}
for (var x = 0; x < 10000; ++x) {
const item = indexedDataset['xx' + 123];
assertEq(item.id, 'xx' + 123);
}
for (var x = 0; x < 10000; ++x) {
const item = dataset[indexMap['xx' + 123]];
assertEq(item.id, 'xx' + 123);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.find | |
indexed copy | |
index map |
Test name | Executions per second |
---|---|
Array.find | 42.2 Ops/sec |
indexed copy | 351.6 Ops/sec |
index map | 261.1 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared options, pros and cons, and other considerations.
Benchmark Overview
The benchmark measures the performance of three different approaches to search for an item in an array of objects: Array.find()
, indexed copy, and index map. The test case creates a large dataset with 100,000 objects, each with a unique ID, and then searches for an object with a specific ID using each approach.
Approaches Compared
id
property of the current item matches the target ID....
) and then searches for the object with the target ID in the copied array.Pros and Cons
Other Considerations
Library/Function Used
In this benchmark, two functions are used:
Array.prototype.find()
: This function is part of the ECMAScript standard and provides a way to search for an item in an array....
): This operator creates a shallow copy of an object or array.Special JavaScript Features
In this benchmark, two special JavaScript features are used:
assertEq()
function is defined using an arrow function, which allows it to be concise and readable while also providing closure over the variable a
and b
.randstr(N)
function uses template literals to generate a random string of length N
.Overall, this benchmark provides valuable insights into the performance characteristics of different approaches to searching for an item in an array of objects, and can help developers choose the most efficient method for their specific use case.