var arr1000 = new Array(1000).fill(0).map((x) => Math.random())
var arr1000000 = new Array(1000000).fill(0).map((x) => Math.random())
const valueFromArray = Array.from(arr1000)
const valueFromSpreading = [arr1000]
const valueFromArray = Array.from(arr1000000)
const valueFromSpreading = [arr1000000]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from (1000 elements) | |
spreading (1000 elements) | |
Array.from (1mil elements) | |
spreading (1mil elements) |
Test name | Executions per second |
---|---|
Array.from (1000 elements) | 77519.3 Ops/sec |
spreading (1000 elements) | 67710.5 Ops/sec |
Array.from (1mil elements) | 43.7 Ops/sec |
spreading (1mil elements) | 13.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided JSON represents a benchmark test case on MeasureThat.net, which compares two approaches to create an array from an existing iterable: Array.from()
and spreading (using the ...
syntax).
Options Compared
Two options are compared:
Array.from()
: A method that creates a new array instance from an existing array-like or iterable object....
syntax to spread elements of an array into a new array.Pros and Cons
Array.from()
:Map
, Set
, etc.).Library Used
In this benchmark, Array.from()
is used in its native form, without any additional libraries or dependencies. The spreading syntax relies on the implicit behavior of JavaScript arrays when using the ...
operator.
Special JS Feature/Syntax
The Map
, Set
, and array-like iterables are not explicitly tested in this benchmark. However, it's worth noting that Array.from()
is designed to work with these types of iterables, while spreading may not produce the expected results.
Benchmark Preparation Code
The provided preparation code creates two large arrays using new Array().fill(0).map((x) => Math.random())
, which are used to test both approaches. The arrays are generated with a mix of 1000 and 1 million elements.
Alternative Approaches
Other approaches to create an array from an iterable include:
slice()
method: arr.slice()
reduce()
method: arr.reduce((acc, x) => [...acc, x], [])
mapValues()
functionThese alternative approaches may offer different trade-offs in terms of performance, readability, and maintainability.