Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Run results for:
npm:fast-cartesian product vs native .reduce() vs cartesian from https://stackoverflow.com/a/43053803
Go to the benchmark
Embed
Embed Benchmark Result
Run details:
User agent:
Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0
Browser:
Firefox 115
Operating system:
Windows 8.1
Device Platform:
Desktop
Date tested:
one year ago
Test name
Executions per second
npm:fast-cartesian
1118.0 Ops/sec
native .reduce() with flatmap, concat
1603977.5 Ops/sec
native .reduce() with map, spread
2631697.8 Ops/sec
cartesian from https://stackoverflow.com/a/43053803
1009096512.0 Ops/sec
Script Preparation code:
var data = [[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]
Tests:
npm:fast-cartesian
// Does a cartesian product on several arrays. // Returns an array with the results. // Optimized to be the fastest implementation in JavaScript. function fastCartesian(arrays) { if (arrays.length === 0) { return [] } const loopFunc = getLoopFunc(arrays.length) const result = [] loopFunc(arrays, result) return result } const getLoopFunc = function (length) { const cachedLoopFunc = cache[length] if (cachedLoopFunc !== undefined) { return cachedLoopFunc } const loopFunc = mGetLoopFunc(length) // eslint-disable-next-line fp/no-mutation cache[length] = loopFunc return loopFunc } const cache = {} // Create a function with `new Function()` that does: // function(arrays, results) { // for (const value0 of arrays[0]) { // for (const value1 of arrays[1]) { // // and so on // results.push([value0, value1]) // } // } // } const mGetLoopFunc = function (length) { const indexes = Array.from({ length }, getIndex) const start = indexes .map((index) => `for (const value${index} of arrays[${index}]) {`) .join('\n') const middle = indexes.map((index) => `value${index}`).join(', ') const end = '}\n'.repeat(length) // eslint-disable-next-line no-new-func return new Function( 'arrays', 'result', `${start}\nresult.push([${middle}])\n${end}`, ) } const getIndex = function (value, index) { return String(index) } const product = fastCartesian(data)
native .reduce() with flatmap, concat
const cartesianProduct = (...allEntries) => allEntries.reduce( (subsetsSoFar, entries) => [ ...subsetsSoFar.flatMap((result) => entries.map((entry) => result.concat([entry]))), ], [[]] ) const product2 = cartesianProduct(data)
native .reduce() with map, spread
function cartesianProductWithSpread(...allEntries) { return allEntries.reduce( (results, entries) => results .map(result => entries.map(entry => [...result, entry] )) .reduce((subResults, result) => [...subResults, ...result] , []), [[]] ) } const product3 = cartesianProductWithSpread(data)
cartesian from https://stackoverflow.com/a/43053803
const cartesian = (...a) => { console.log(a) return a.reduce((a, b) => a.flatMap(d => { // console.log(b) return b.map(e => [d, e].flat()) }))}