var fooSet = new Set();
for(var i=0;i<100000;i++) {
fooSet.add(i);
}
var other = Array.from(fooSet);
var fooSet = new Set();
for(var i=0;i<100000;i++) {
fooSet.add(i);
}
var other = [fooSet];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Spread |
Test name | Executions per second |
---|---|
Array.from | 66.4 Ops/sec |
Spread | 67.5 Ops/sec |
Let's dive into explaining the provided benchmark and its results.
Benchmark Definition
The benchmark is defined as Array.from vs Spread Performance
, which compares the performance of two approaches: using Array.from()
and using the spread operator (...
).
Options Compared
Two options are compared:
Array.from()
: This method creates a new array from an iterable (in this case, a Set) by iterating over its values....
): This method creates a new array from an iterable (in this case, a Set) by creating a shallow copy of its values.Pros and Cons
...
):Library Used
In this benchmark, no external libraries are used. However, it's worth noting that both Array.from()
and the spread operator work by leveraging built-in JavaScript features.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax being tested in this benchmark. Both approaches rely on standard JavaScript constructs (sets, arrays, iteration).
Other Alternatives
If you're interested in exploring alternative approaches for creating arrays from iterables, here are a few options:
map()
: You can use the map()
method to create an array from an iterable.reduce()
: Alternatively, you can use the reduce()
method to accumulate values into an array.Example:
var array = [...new Set([1, 2, 3, 4, 5])];
// or
var array = Array.prototype.map.call(new Set([1, 2, 3, 4, 5]), x => x);
Keep in mind that these alternatives may have slightly different performance characteristics compared to Array.from()
and the spread operator.
Benchmark Results
The latest benchmark results show that the spread operator (...
) performs slightly better than Array.from()
, with an average execution rate of approximately 67.55 executions per second (Spread) vs. 66.45 executions per second (Array.from()). However, these performance differences are typically negligible and should not impact the overall performance of your application.
In summary, this benchmark provides a simple comparison between two approaches for creating arrays from iterables in JavaScript. While there may be slight performance differences between Array.from()
and the spread operator, both methods have their pros and cons and can be used depending on the specific use case.