var testIterable = function* generateIterable() {
for (let i = 0; i < 100; i++) {
yield i;
}
}
const arr = Array.from(testIterable());
const arrs = Array.prototype.slice.call(testIterable());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
Array slice |
Test name | Executions per second |
---|---|
Array.from | 334720.8 Ops/sec |
Array slice | 1929691.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
What is being tested?
The benchmark measures the performance of two approaches to create an array from an iterable:
Array.from()
Array.prototype.slice.call()
(often referred to as "array slice")In this specific case, the test case uses a generator function testIterable
to generate an array of numbers from 0 to 99.
Options compared
The benchmark compares two options for creating an array from an iterable:
Array.from()
: This method creates a new array from an iterable (such as an array, object, or any other type of iterable) by mapping each element to a new array value.Array.prototype.slice.call()
(or simply "array slice"): This approach uses the slice()
method on an array and then passes the result to call()
with an array of arguments.Pros and Cons
Here are some pros and cons of each approach:
Array.from()
:Array.prototype.slice.call()
(array slice):slice()
method.Array.from()
.call()
.Library usage
In this benchmark, no external libraries are used. However, if you were to extend this benchmark to compare other approaches, you might consider using libraries like Lodash or Ramda, which provide a range of utility functions for working with arrays and iterables.
Special JavaScript feature/syntax
There is no special JavaScript feature or syntax mentioned in this benchmark. The test cases rely solely on standard JavaScript features and syntax.
Other alternatives
If you wanted to compare other approaches to creating an array from an iterable, some possible alternatives could include:
Array.prototype.concat()
to concatenate multiple iterables.Keep in mind that each of these alternative approaches would have its own pros and cons, which would need to be carefully considered when designing a benchmark.