var arr = Array.from(Array(1000).keys()).map(i => Math.random())
arr.reduce((acc, item) => [acc, ],[])
arr.reduce((acc, item) => {
acc.push(item);
return acc;
},[])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
Push |
Test name | Executions per second |
---|---|
Spread | 125504.6 Ops/sec |
Push | 336014.4 Ops/sec |
I'd be happy to help you understand the JavaScript microbenchmark on MeasureThat.net.
What is being tested?
The provided benchmark compares two approaches for reducing an array: using the spread operator (arr.reduce((acc, item) => [...acc, ],[])
for "Spread") and using the push
method (arr.reduce((acc, item) => { acc.push(item); return acc; },[])
for "Push").
Options compared:
acc
) with each element of the original array.push
method is used to add one or more elements to the end of an array.Pros and Cons:
Library usage:
There is no explicit library used in this benchmark. However, the Array.from()
method is used to create an array from an iterable (in this case, an array with random values).
Special JS feature or syntax:
Array.from()
is a static method that creates a new array from an iterable.Benchmark preparation code:
The script preparation code generates an array of 1000 random numbers using Array.from(Array(1000).keys()).map(i => Math.random())
.
Test cases:
There are two test cases:
push
method to reduce the array.Latest benchmark result:
The results show that Chrome 112 on a desktop with Windows OS performs better for the "Push" approach, while the spread operator is faster for the "Spread" approach.
Other alternatives:
Alternative approaches to reducing an array in JavaScript include:
forEach()
or map()
: These methods can be used to transform arrays, but may not be suitable for reduction.Keep in mind that the performance differences between these approaches may depend on the specific use case, data size, and browser/OS being used.