Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
flatten reduce vs for .. of vs reduce TCO v2
(version: 0)
Comparing performance of:
reduce vs for of vs reduce TOC
Created:
2 years ago
by:
Guest
Jump to the latest result
Script Preparation code:
const get = (depth = 0) => { const arr = []; if (depth > 100) { // Stop recursion beyond depth 2 return arr; // Return an empty array to avoid undefined entries } for (let i = 0; i < 10; i++) { // Reduced loop count for demonstration if (Math.random() > 0.2) { // Recursively call get(), but wrap the result in an array to ensure arrays are nested within arr.push([get(depth + 1)]); } else { // Create a sub-array of numbers const numberArray = []; for (let j = 0; j < 100; j++) { numberArray.push(Math.floor(Math.random() * 100)); } // Decide randomly to push the whole array or individual numbers if (Math.random() > 0.5) { arr.push(numberArray); // Push the array as a single element } else { arr.push(...numberArray); // Spread the array into individual elements } } } return arr; }; var array = get(99)
Tests:
reduce
const flatten = (arr) => arr.reduce((acc, x) => { Array.isArray(x) ? flatten(x).forEach(y => acc.push(y)) : acc.push(x) return acc; }, []) const x = flatten(array);
for of
const flat = (argarr) => { let arr = [] for (const item of argarr) { if (Array.isArray(item)) arr = arr.concat(flat(item)) else arr.push(item) } return arr } const x = flat(array);
reduce TOC
const flatten = (arr, acc = []) => { arr.forEach(x => { if (Array.isArray(x)) { flatten(x, acc); } else { acc.push(x); } }); return acc; }; const x = flatten(array);
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (3)
Previous results
Fork
Test case name
Result
reduce
for of
reduce TOC
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
2 years ago
)
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.1 Safari/605.1.15
Browser/OS:
Safari 16 on Mac OS X 10.15.7
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
reduce
5671.4 Ops/sec
for of
7110.2 Ops/sec
reduce TOC
6261.7 Ops/sec
Autogenerated LLM Summary
(model
llama3.2:3b
, generated one year ago):
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons. **Benchmark Definition** The benchmark is defined by three approaches to flatten an array: 1. `for...of` loop 2. `Array.prototype.reduce()` method with a custom callback function (`flatten TOC`) 3. A simple recursive function using a loop (`reduce`) These three approaches are being compared in terms of performance, and the goal is to determine which one is the most efficient. **For...of Loop** The for...of loop approach uses an iterative approach to flatten the array. It iterates over each element in the array and checks if it's an array itself. If it is, the function calls itself recursively with the inner array as an argument. If not, it simply pushes the element onto the result array. Pros: * Easy to implement and understand * No need for a callback function or memoization Cons: * Can be slow due to the recursive call * May lead to stack overflow errors if the recursion depth is too high **Array.prototype.reduce() Method** The `reduce()` method approach uses the built-in `reduce()` method of arrays. The custom callback function (`flatten`) takes two arguments: the accumulator (the result array) and the current element being processed. Pros: * Fast and efficient, as it's a built-in method optimized for performance * Can be memoized to cache intermediate results Cons: * Requires knowledge of the `reduce()` method implementation and its callback function * May require additional setup to handle edge cases (e.g., empty arrays) **Recursive Function** The recursive function approach uses a simple loop to flatten the array. It takes an optional accumulator parameter, which is used to store the result. Pros: * Easy to implement and understand * No need for a callback function or memoization Cons: * Can be slow due to the recursion * May lead to stack overflow errors if the recursion depth is too high **Library Used** The benchmark uses the `Array.prototype.forEach()` method, which is part of the ECMAScript standard. This method iterates over each element in an array and executes a provided callback function once for each element. **Special JS Features or Syntax** None mentioned. **Other Alternatives** Other approaches to flatten arrays include: * Using `Spread Operator` (`...`): `const flattenedArray = [...array]` * Using `Array.prototype.map()` method: `const flattenedArray = array.map(item => item);` These alternatives may offer different performance characteristics or trade-offs in terms of simplicity and readability. **Benchmark Results** The latest benchmark results show the number of executions per second for each approach: 1. For...of loop: 7110.16357421875 2. Reduce TOC (with callback function): 6261.736328125 3. Reduce: 5671.4208984375 These results suggest that the `for...of` loop approach is the fastest, followed closely by the `reduce()` method approach with a custom callback function (`TOC`). The simple recursive function approach is slower. Keep in mind that these results may vary depending on the specific use case, input data, and JavaScript engine used.
Related benchmarks:
Array creation with Array.reduce vs for loop vs Array.forEach
Array creation with Array.reduce vs for loop vs Array.forEach(2)
Array.reduce vs for loops vs Array.forEach
Array flatten implementations [high volume]
Comments
Confirm delete:
Do you really want to delete benchmark?