Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Run results for:
flatten reduce vs for .. of vs reduce TCO v2
Go to the benchmark
Embed
Embed Benchmark Result
Run details:
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:
Safari 16
Operating system:
Mac OS X 10.15.7
Device Platform:
Desktop
Date tested:
2 years ago
Test name
Executions per second
reduce
5671.4 Ops/sec
for of
7110.2 Ops/sec
reduce TOC
6261.7 Ops/sec
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);