globalThis.map = []
globalThis.objArr = []
for (let i = 0; i < 20; i++) {
const shardKey = String(i).slice(0,2)
if (!map[`thing-${shardKey}`]) map[`thing-${shardKey}`] = []
map[`thing-${shardKey}`][String(i)] = { i }
objArr.push({ i })
}
const v = map['thing-5']['5']
console.log(v)
delete map['thing-5']['5']
for (let i = objArr.length - 1; i >= 0; i--) {
const v = objArr[i]
if (v.i === 5) {
objArr.splice(i, 1)
console.log(v)
return v
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
string map | |
find |
Test name | Executions per second |
---|---|
string map | 68488.0 Ops/sec |
find | 200049.1 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, and their pros and cons.
What's being tested:
The benchmark is comparing two approaches for searching an array:
map
with string keys and values that are arrays of objects containing a single property i
. The search query uses the bracket notation to access a specific value in the array.objArr
and performs a for loop iteration from the end to find a specific element based on its index.Options compared:
The two options being compared are:
Pros and Cons of each approach:
Library used:
The benchmark uses a JavaScript object map
which is not part of the standard library. It's likely that this object is a custom implementation or a polyfill for a specific use case.
Special JS feature/syntax:
There are no special features or syntaxes being tested in this benchmark.
Other alternatives:
Other approaches to search arrays could include:
Array.prototype.indexOf()
and Array.prototype.splice()
Map
objects (if the browser supports them)Object.keys()
, JSON.parse()
, and Array.from()
It's worth noting that the performance difference between these approaches can be significant, especially for large arrays. The String Map approach is generally faster due to its optimized data structure and direct access to elements.