var arr = Array(10_000).fill(0)
arr.reduce((acc, x) => [acc, x, x], [])
arr.reduce((acc, x) => { acc.push(x); return acc; }, [])
arr.reduce((acc, x) => acc.concat(x), [])
const newArray = [];
for (let i = 0; arr.length > i; i++) {
newArray.push(arr[i]);
}
const newArray = [];
for (let x of arr) {
newArray.push(x);
}
arr.map(x => x);
const newArray = [];
arr.forEach(x => newArray.push(x));
const newArray = [];
for (let x of arr.values()) {
newArray.push(x);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with new array | |
reduce with array mutation | |
reduce with array concat | |
for | |
for-of | |
map | |
forEach | |
values (iterates over for-of) |
Test name | Executions per second |
---|---|
reduce with new array | 10.3 Ops/sec |
reduce with array mutation | 20414.3 Ops/sec |
reduce with array concat | 6.3 Ops/sec |
for | 720.2 Ops/sec |
for-of | 32640.4 Ops/sec |
map | 28712.2 Ops/sec |
forEach | 20057.6 Ops/sec |
values (iterates over for-of) | 32086.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided benchmark, "Array processing benchmark," measures the performance of different approaches to process arrays in JavaScript. The test consists of six individual test cases:
reduce
with new arrayreduce
with array mutationreduce
with array concatTest Case Analysis
Each test case has a unique approach to process the array, and the benchmark measures the performance of each approach.
reduce
with new array: This test creates a new array and pushes elements from the original array onto it using push()
.reduce
with array mutation: Similar to the previous one, but the reduce()
method modifies the original array by appending elements to it directly.reduce
with array concat: This test uses concat()
to concatenate arrays instead of pushing elements onto an array or directly modifying the array.for
loop to iterate over the array and push elements onto a new array.for...of
loop instead.for
loops.map()
method to create a new array with transformed elements from the original array.Library and Special Features
Other Alternatives
If you're looking for alternative approaches to process arrays, consider the following:
forEach()
: Similar to for...of
, but without the iterator benefits. May not be suitable for very large arrays.filter()
, sort()
, and other array methods: While these methods are useful, they may not provide the same performance as optimized approaches like reduce()
or map()
.while
loops or recursive functions.In conclusion, when it comes to processing arrays in JavaScript, the choice of approach depends on your specific requirements and constraints. Understanding the pros and cons of each method can help you make informed decisions about which approach to use for your particular use case.