function setup() {
const randInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min);
const itemMap = {};
const itemArr = [];
for (let i = 0; i < 10000; i++) {
const item = {
id: randInt(0, 1000000),
value: `value-${randInt(0, 1000000)}`
};
itemArr.push(item);
itemMap[item.id] = item;
}
const itemIdsToGet = [itemArr[8002].id, itemArr[2423].id, itemArr[5322].id, itemArr[3].id, itemArr[7242].id]
return {
itemIdsToGet,
itemMap,
itemArr
}
}
const values = setup();
for (const itemIdToUpdate of values.itemIdsToGet) {
values.itemMap[itemIdToUpdate].value = 'updated'
}
const values = setup();
for (const itemIdToUpdate of values.itemIdsToGet) {
const index = values.itemArr.findIndex(x => x.id === itemIdToUpdate);
values.itemArr[index].value = 'updated';
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
array |
Test name | Executions per second |
---|---|
map | 177.5 Ops/sec |
array | 182.3 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks, comparing the performance of different approaches for various use cases.
The provided benchmark definition represents a test case where two methods are compared:
Options Compared
The two options being compared are:
array
: The "array" option, which uses an array to store and update values. In this case, it finds the index of the item in the array using findIndex()
and then updates the value at that index.map
: The "map" option, which uses an object literal (map) to store and update values.Pros and Cons
findIndex()
and array indexing, which can be slower than object literal (map) lookup.Library Used
In this benchmark, no libraries are explicitly mentioned, but the use of findIndex()
and array indexing suggests that JavaScript's built-in Array methods are being used.
Special JS Feature or Syntax
There is no special JavaScript feature or syntax used in this benchmark. It's a straightforward implementation of two common approaches to updating values in arrays.
Other Alternatives
If you wanted to test other alternatives, here are some options:
forEach()
instead of findIndex()
and array indexingNote that the performance characteristics of these alternatives would depend on the specific use case and requirements.