var map = new Map();
var arrLookup = [];
var items = [];
for (var i = 0; i < 100; i++) {
items[i] = [];
for (var j = 0; j < 100; j++) {
items[i][j] = [i,j];
if (Math.random() < 0.1) {
map.set(i+","+j, Math.random()>=0.5);
if (!arrLookup[i]) arrLookup[i] = [];
arrLookup[i][j] = Math.random()>=0.5;
}
}
}
var results = [], i, j;
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
if (map.has(items[i][j] +"")) results.push(map.get(items[i][j]+""));
}
}
if (results.length === 0) throw Error();
var results = [], i, j;
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
if (arrLookup[i] && typeof arrLookup[i][j] !== "undefined") results.push(arrLookup[i][j]);
}
}
if (results.length === 0) throw Error();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map lookup | |
Array lookup |
Test name | Executions per second |
---|---|
Map lookup | 397.2 Ops/sec |
Array lookup | 15354.5 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition
The website tests two different approaches to perform a look-up operation: using an array (arrLookup
) and using a Map
data structure (map
).
In the script preparation code, we see:
items
(which contains nested arrays) and arrLookup
.items
array with 100x100 nested arrays.items
array, we randomly decide whether to add an element to both map
and arrLookup
. If we choose to add it to map
, we use the string representation of the key (i+","+j
) to store a random value.Options Compared
We have two options:
arrLookup
using their index (items[i][j]
). This approach is straightforward but may be slower for large arrays.has()
and get()
methods of the map
object to look up values by key. This approach provides faster lookup times, especially when dealing with a large number of keys.Pros and Cons
Map
lookup when dealing with large amounts of data.map
object.Library/Feature
The benchmark uses JavaScript's built-in Map
data structure. The purpose of this library is to provide a fast and efficient way to store and retrieve key-value pairs in JavaScript.
Special JS Features/Syntax
There are no special features or syntax used in this benchmark that would require additional explanation.
Alternatives
If you wanted to compare these approaches, you could also consider using other data structures like:
Keep in mind that the performance differences between these approaches will depend on the specific use case and the size of the data being processed.