globalThis.map = []
globalThis.objArr = []
for (let i = 0; i < 10000; 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-10']['100']
console.log(v)
delete map['thing-10']['100']
for (let i = objArr.length - 1; i >= 0; i--) {
const v = objArr[i]
if (v.i === 100) {
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 | 176048.8 Ops/sec |
find | 491.6 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark measures the performance of two different approaches to search and manipulate data in JavaScript:
objArr
containing 10,000 objects, each with an i
property. It then populates a string map map
with the same data, but only for a subset of indices (thing-10
and thing-20
). Finally, it searches for a specific value in the string map using the key 'thing-10'['100']
.objArr
in reverse order, checking each element's i
property until it finds a match.Options Compared
The two approaches are compared in terms of their execution time:
Pros and Cons of Each Approach
Library and Special JS Features
In this benchmark, there is no explicit library used. However, some JavaScript features are used:
const v = map['thing-10']['100']
line to create a string template.Other Alternatives
If you want to explore alternative approaches, here are some options:
objArr
. This would reduce the time complexity to O(log n), but requires a sorted array.objArr
without using a loop, you could sort the array first and then use a binary search algorithm.Keep in mind that each alternative approach would affect the benchmark's results and interpretation.