Last active
March 6, 2025 17:08
-
-
Save MRobertEvers/5763fe145c6cccab6c199fda19ac94ad to your computer and use it in GitHub Desktop.
Reduce N2 Behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function _map1(arr) { | |
return arr.reduce((acc, item) => { | |
acc[item] = item | |
return acc | |
}, {}) | |
} | |
function _map2(arr) { | |
return arr.reduce((acc, item) => ({ ...acc, [item]: item }), {}) | |
} | |
for (let i = 0; i < 3000; i++) { | |
const testArr1 = new Array(i).fill(0).map((_, i) => i) | |
const testArr2 = new Array(i).fill(0).map((_, i) => i) | |
// Start a timer | |
const start1 = performance.now() | |
_map1(testArr1) | |
const end1 = performance.now() | |
console.log(`_map1(${i}): ${end1 - start1}ms`) | |
const start2 = performance.now() | |
_map2(testArr2) | |
const end2 = performance.now() | |
console.log(`_map2(${i}): ${end2 - start2}ms`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
_map1(2991): 0.033250004053115845ms
_map2(2991): 1.451457992196083ms
_map1(2992): 0.034750014543533325ms
_map2(2992): 1.5427920073270798ms
_map1(2993): 0.03154100477695465ms
_map2(2993): 1.3232919871807098ms
_map1(2994): 0.02779199182987213ms
_map2(2994): 1.305416002869606ms
_map1(2995): 0.03291599452495575ms
_map2(2995): 1.3136669993400574ms
_map1(2996): 0.08095800876617432ms
_map2(2996): 1.5040830075740814ms
_map1(2997): 0.030125007033348083ms
_map2(2997): 1.4211250096559525ms
_map1(2998): 0.04133300483226776ms
_map2(2998): 1.4392080008983612ms
_map1(2999): 0.03491699695587158ms
_map2(2999): 1.2444579899311066ms