function generateAnArray(gvv) {
let arr = [];
for(let i = 0; i < 100; i++) {
arr.push([i + '', {
id: i,
value: `value${i}`
}]);
}
return arr;
}
bar = generateAnArray();
function generateArray() {
let arr = [];
for(let i = 0; i < 100; i++) {
arr.push([i + '', {
id: i,
value: `value${i}`
}]);
}
return arr;
}
const foo = new Map(generateArray());
bar.reduce((arr, rr) => arr.set(rr[0], rr), new Map())
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
arry first | |
add to map |
Test name | Executions per second |
---|---|
arry first | 258646.4 Ops/sec |
add to map | 436094.5 Ops/sec |
Let's dive into the provided benchmarking data.
What is being tested?
The benchmark measures how fast different approaches can create and populate a JavaScript Map
object, which is essentially an unordered collection of key-value pairs.
Options compared:
There are two test cases:
generateArray()
function to generate an array of arrays, where each inner array has an id
and a value
. The resulting array is then passed directly to the Map
constructor using the spread operator (const foo = new Map(generateArray());
). This approach creates the map without explicitly setting any values.reduce()
method is used to iterate over the generated array and set each value in a separate call to set()
, like this: bar.reduce((arr, rr) => arr.set(rr[0], rr), new Map())
. This approach explicitly sets each value in the map.Pros and Cons of each approach:
set()
calls)set()
calls)Other considerations:
When working with Map
objects in JavaScript, it's essential to consider factors such as:
Library/Library purpose:
None of the provided benchmarking code uses any external libraries. However, if we were to extend this example with additional libraries or modules, we might consider using a library like lodash
(specifically its mapValues()
function) to simplify map creation and iteration:
const _ = require('lodash');
// ...
bar = new Map(_.map(generateArray(), rr => ({ id: rr[0], value: rr[1] })));
Special JS feature/Syntax:
There is no explicit use of any special JavaScript features or syntax in the provided code.
In summary, this benchmark measures how fast two different approaches can create and populate a JavaScript Map
object. The "arry first" approach provides a simple, efficient solution but might lack readability for complex use cases, while the "add to map" approach offers more control over mapping logic but incurs additional overhead due to multiple set()
calls.