const createLists = (arr = []) => {
const listMap = new Map();
for (const val of arr) {
if (!listMap.has(val)) {
listMap.set(val, [val]);
continue;
}
listMap.get(val).push(val);
}
return Array.from(listMap.values());
};
console.log(createLists([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0]));
function createLists(arr = []) {
let authors = [];
let list = [];
arr.forEach(item => {
let authorIndex = authors.includes(item) ? authors.indexOf(item) : (authors.push(item) - 1);
list[authorIndex] = list[authorIndex] || [];
list[authorIndex].push(item);
});
return list;
}
console.log(createLists([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map | |
forEach |
Test name | Executions per second |
---|---|
Map | 32319.3 Ops/sec |
forEach | 47775.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The provided JSON represents two benchmark definitions:
Map vs forEach
: This is the overall name and description of the benchmark, which compares the performance of using a Map
data structure versus iterating over an array using forEach
.createLists(arr = []) => { ... }
: This is a JavaScript function that creates lists from an input array.function createLists(arr = []) { ... }
: This is another implementation of the same function, using forEach
.Options Compared
The benchmark compares two options:
Map
data structure to group elements by their values.forEach
, which creates a new list with grouped elements.Pros and Cons of Each Approach
Map:
Pros:
Cons:
forEach:
Pros:
Cons:
Library Used
In this benchmark, no libraries are explicitly mentioned. However, it's worth noting that Map
is a built-in JavaScript data structure, while forEach
is also a native method.
Special JS Feature or Syntax
The benchmark uses JavaScript functions and closures, but does not specifically highlight any advanced features like async/await, Promises, or modern syntax like arrow functions. The focus is on the performance comparison between two basic algorithmic approaches.
Other Alternatives
If you're interested in exploring other performance optimization techniques for similar problems, consider:
Set
instead of a Map
if the order of elements doesn't matter.Array.prototype.reduce()
).