var string = '1'.repeat(1000);
const array = Array.from(string, x => x * 2);
const array = [string].map(x => x * 2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
[...spread] |
Test name | Executions per second |
---|---|
Array.from | 48481.1 Ops/sec |
[...spread] | 80607.6 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance difference between two approaches for converting a string to an array: Array.from()
and the spread syntax [...spread]
.
Approaches Compared
There are two test cases:
Array.from()
: This method creates a new array from an existing iterable (like a string) by calling its iterator. It takes a callback function (x => x * 2
) that is applied to each element of the string.[...spread]
: This syntax uses the spread operator (...
) to create a new array from an existing iterable (like a string). The callback function (x => x * 2
) is also applied to each element of the string, similar to Array.from()
.Pros and Cons
Array.from()
:[...spread]
:Array.from()
.Array.from()
because it doesn't involve a function call.Other Considerations
Array.from()
and spread syntax.Special JS Features/Syntax
None are explicitly used or compared in this benchmark. It sticks strictly to standard JavaScript features and syntax.
Alternatives
Other approaches for converting strings to arrays include:
map()
: While similar to the spread syntax, it uses a function call and is generally slower than the spread operator for large arrays.reduce()
: This method applies a reduction function to an array (like a string) and returns the accumulated value. It's less suitable for simple conversions like this benchmark.Benchmarking
The provided test cases aim to compare these two approaches on performance, specifically focusing on how they handle iteration over large strings. The results of each test case can provide insights into which approach is generally more efficient in different scenarios.