var map = new Map();
for(var i=0;i<100;i++) {
map.set(100-i, i);
}
var sortedMap = new Map(Array.from(map.entries()).sort((a, b) => a[0] - b[0]));
var map = new Map();
for(var i=0;i<100;i++) {
map.set(100-i, i);
}
var sortedMap = new Map([map.entries()].sort((a, b) => a[0] - b[0]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Spread |
Test name | Executions per second |
---|---|
Array.from | 74050.5 Ops/sec |
Spread | 72921.2 Ops/sec |
Let's dive into the explanation.
The provided JSON represents a benchmark test on MeasureThat.net, which compares two approaches for creating a sorted Map from an array of key-value pairs: using Array.from()
and using the spread operator (...
).
Benchmark Definition
The benchmark definition is a simple script that creates a new Map, populates it with entries using a loop, and then sorts the Map based on its keys. There are two variations:
...
) to convert the Map.entries()
array into an array of key-value pairs.Array.from()
method to create a new array from the Map.entries()
iterator.Options Comparison
The two options are compared in terms of their performance, which is measured by the number of executions per second.
Library Usage
Neither option uses a library. However, both use the built-in Map
and Array.from()
methods.
Special JS Feature/Syntax
This benchmark does not require any special JavaScript features or syntax that would be unfamiliar to most software engineers.
Other Alternatives
If you want to create a sorted Map from an array of key-value pairs without using Array.from()
or the spread operator, you can use other approaches:
reduce()
: Create a new array by reducing the Map.entries()
iterator into an array.forEach()
: Iterate over the Map.entries()
iterator and create a new array by pushing each entry into it.In conclusion, this benchmark tests two approaches for creating a sorted Map from an array of key-value pairs: using Array.from()
and using the spread operator. The choice between these options depends on performance considerations and compatibility with older browsers.