const array = window.array = []
for (let i = 1000; i; --i) array.push(i)
window.a = Array.from(array)
window.b = Array.from(array)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Spread |
Test name | Executions per second |
---|---|
Array.from | 37145.9 Ops/sec |
Spread | 39450.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The benchmark measures the performance difference between two approaches: using Array.from()
and spreading an array (...array
) to create a new copy.
Options being compared
Two options are being compared:
Array.from(array)
: This approach uses the Array.from()
method, which takes an iterable (in this case, the array
variable) as an argument and returns a new array containing all elements from the original iterable....array
): This approach uses the spread operator (...
) to create a new array by copying all elements from the original array
.Pros and Cons of each approach
Array.from(array)
:...array
):In general, Array.from()
can be a good choice when you need more control over the created array or when working with older browsers that don't support the spread operator. However, spreading an array using the ...
operator can be faster in modern browsers.
Library and purpose
None mentioned in this specific benchmark definition.
Special JS feature or syntax
The spread operator (...
) is used in both test cases. The spread operator was introduced in ECMAScript 2015 (ES6) as a concise way to create a new array by copying elements from an existing array. It's supported in modern browsers and Node.js versions starting from ES6.
Other alternatives
If you want to explore other approaches, here are some alternatives:
slice()
or map()
with an empty callback function to create a shallow copy of the array: Array.prototype.slice.call(array)
or array.map(() => {})
.JSON.parse(JSON.stringify(array))
(not recommended due to security concerns and performance overhead).cloneDeep()
or _.clone()
.Keep in mind that these alternatives might have different performance characteristics and trade-offs, so it's essential to test them thoroughly for your specific use case.