var data = new Array(15000);
data = data.fill({ id: 0 }).map((el, idx) => el.id = idx);
var mapData = new Map(data.map(obj => [obj.id, obj]))
var setData = new Set(data)
var recId = Math.floor(Math.random() * 15000);
var findInSet = (obj, testFn) => {
for (var item of obj) if(testFn(item)) return item;
}
var matchFn = (obj) => obj.id === recId
var index = data.findIndex((num) => num === recId);
var index = data.indexOf(recId);
var index = data.filter((obj) => obj.id === recId);
var index = data.find((obj) => obj.id === recId);
var index = mapData.get(recId);
var index = setData.has(data[recId]);
var index = findInSet(setData, matchFn);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Arr - findIndex | |
Arr - indexOf | |
Arr - filter | |
Arr - find | |
Map - get | |
Set - has | |
Set - findInSet |
Test name | Executions per second |
---|---|
Arr - findIndex | 1582.8 Ops/sec |
Arr - indexOf | 1243520.0 Ops/sec |
Arr - filter | 488.9 Ops/sec |
Arr - find | 487.9 Ops/sec |
Map - get | 4078419.8 Ops/sec |
Set - has | 2808695.0 Ops/sec |
Set - findInSet | 578.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition and Script Preparation Code
The benchmark definition represents a JavaScript function that performs a search operation on an array, map, or set data structure. The script preparation code generates a large array, map, and set with 15,000 elements each, filled with random data. A random index recId
is generated, which will be used as the target value for the search operations.
The script preparation code also defines two functions: findInSet
, which performs a custom search operation on the set data structure, and matchFn
, which takes an object as input and returns true
if its id
property matches the recId
.
Individual Test Cases
There are six test cases, each representing a different search operation:
Array.prototype.findIndex
.Array.prototype.indexOf
.Array.prototype.find
.Map.prototype.get
.Set.prototype.has
.findInSet
function.Comparison of Options
Here's a brief overview of each option and their pros and cons:
findIndex
, but returns -1
if the target value is not found. It's slightly slower than findIndex
.find
.Other Considerations
When interpreting benchmark results, keep in mind:
Overall, this benchmark compares different search operations on arrays, maps, and sets in JavaScript. Understanding the pros and cons of each option can help you choose the best approach for your specific use case.