var fooMap = new Map(); for(var i=0;i<10000;i++) { fooMap.set(i, i); } var other = [fooMap];
var fooMap = new Map(); for(var i=0;i<10000;i++) { fooMap.set(i, i); } var other = fooMap.keys();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Map.keys |
Test name | Executions per second |
---|---|
Array.from | 1063.4 Ops/sec |
Map.keys | 2314.7 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Definition
The benchmark is defined by two test cases: Array.from()
and Map.keys()
. These are both methods used to convert an iterable (like an array or map) into a new array or object. The main difference between them lies in how they approach this conversion:
Array.from()
: This method creates a new array from an iterable or an array-like object. It takes an iterable as an argument and returns a new array with the elements of that iterable.Map.keys()
: This method returns a iterator over the keys of a map (an object that stores key-value pairs). This iterator can be used to create a new iterable, like an array.Options Compared
The benchmark is comparing two approaches:
Array.from()
to convert a map into an array.Map.keys()
directly to get an iterator over the keys of the map and then creating an array from that iterator.Pros and Cons
Here are some pros and cons for each approach:
Using Array.from()
:
Map.keys()
)Using Map.keys()
:
Array.from()
.Library Used
In this benchmark, none are explicitly stated as used by test users. However, in JavaScript Map
and its methods like keys()
and values()
, are built-in.
Special JS Feature or Syntax
The feature used here is that of using Map
object, which is a fundamental part of the JavaScript standard library for working with collections of key-value pairs. It was introduced in ECMAScript 2015 (ES6).
Other Alternatives
There are several other ways to convert an iterable into a new array or object:
Array.prototype.slice()
or Array.from().slice()
: These methods create a shallow copy of the input array, but they can be slower than using Array.from()
.String.prototype.split()
: This method splits a string into an array of substrings.Array.prototype.map()
and Array.prototype.reduce()
: These methods can be used to transform an iterable into an array. However, they are more computationally expensive than using Array.from()
.