var fooMap = new Map();
for(var i=0;i<10000000;i++) {
fooMap.set(i, { id: i });
}
var other = Array.from(fooMap, ([name, value]) => value);
var other = [fooMap].map(([name, value]) => value);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Spread |
Test name | Executions per second |
---|---|
Array.from | 3.9 Ops/sec |
Spread | 1.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches to iterate over a Map object in JavaScript:
Array.from
...
)The goal is to find out which approach is faster, more efficient, or has better performance for this specific use case.
What's Being Tested?
In the Script Preparation Code
, we have a Map object fooMap
created with 10 million entries. The purpose of this code is to populate the map with data that will be used in the subsequent test cases.
The two test cases compare how long it takes for each approach to:
[...]
) or Array.from
functionOptions Compared
Let's break down the options being compared:
Array.from
This method creates a new Array instance and populates it with the elements of the original map.
var other = Array.from(fooMap, ([name, value]) => value);
Pros:
Cons:
...
)This method uses the spread operator to create a new array from the elements of the original map.
var other = [...fooMap].map(([name, value]) => value);
Pros:
Array.from
Cons:
Array.from
in certain situationsLibrary Used
In both test cases, we're using the Map
data structure from JavaScript's built-in Object
namespace. The purpose of this library is to provide a simple way to store key-value pairs and iterate over them efficiently.
Special JS Feature or Syntax
There are no special features or syntax used in this benchmark that require a specific understanding of advanced JavaScript concepts. However, the use of Map
and the spread operator may be unfamiliar to developers who haven't worked with these data structures before.
Other Alternatives
If you wanted to write a similar benchmark, you could consider adding additional test cases for other approaches, such as:
for...in
loopforEach()
methodmapKeys()
functionHowever, keep in mind that each alternative approach may have its own pros and cons, and may not necessarily outperform the existing options.
Benchmark Preparation Code
The provided script preparation code is used to create a Map object with 10 million entries. This code is executed before running the benchmark test cases.
var fooMap = new Map();
for (var i = 0; i < 10000000; i++) {
fooMap.set(i, { id: i });
}
This code creates a Map object and populates it with data that will be used in the subsequent test cases.