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(i+","+j)) results.push(map.get(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 | 476.2 Ops/sec |
Array lookup | 585.2 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Definition JSON
The benchmark is designed to compare two approaches: using a Map
data structure for key-value storage versus accessing an array with indexed lookup.
Here's what's being tested:
map
) is created, which stores key-value pairs.arrLookup
) is also created, which will be used as an alternative data structure for key-value storage.items
(arrays) is generated, with each item containing another array of 100 elements.items
array, there's a 10% chance that the corresponding value in the map or arrLookup will be set. The value is randomly generated and has a 50% chance of being a random number.Test Cases
There are two individual test cases:
map
data structure to access its values.results
to store the retrieved values.items
array and checks if a value exists in the map using the has()
method. If it does, the corresponding value is pushed onto the results
array using the get()
method.arrLookup
array data structure to access its values.results
to store the retrieved values.items
array and checks if the corresponding value exists in arrLookup using a conditional statement (typeof arrLookup[i][j] !== "undefined"
). If it does, the value is pushed onto the results
array.Options Compared
The two test cases are comparing the performance of:
Map
data structure for key-value storage (Map lookup)Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Map
.Map
data structure.Other Considerations
Map
data structure provided by JavaScript. No additional libraries are required for this benchmark.Alternatives
If you want to explore alternative approaches, consider the following:
Map
data structure.Map
for fast lookups, but at the cost of higher memory usage.Keep in mind that these alternatives might require significant modifications to your benchmark code.