Skip to content

Instantly share code, notes, and snippets.

@matyasfodor
Created October 9, 2018 11:31
Show Gist options
  • Save matyasfodor/9edee0874eee5c167a9f3a51de87e475 to your computer and use it in GitHub Desktop.
Save matyasfodor/9edee0874eee5c167a9f3a51de87e475 to your computer and use it in GitHub Desktop.
Performance test for assign vs reduce
const randString = () => Math.random().toString(36).substring(7);
const gen = (n) =>
new Array(n).fill(1).map(() => ({key: randString(), value: Math.random()}));
const array1 = gen(100);
const array2 = gen(1000);
const array3 = gen(100000);
const assign = (arr) =>
Object.assign(
{},
...(arr.map(({key, value}) => ({[key]: value}))),
);
const reduce = (arr) =>
arr.reduce((acc, {key, value}) => ({...acc, [key]: value}), {});
function perf(label, arr, func) {
t0 = performance.now();
func(arr);
t1 = performance.now();
console.log(`${label} took ${t1 - t0} ms to finish`)
}
perf('100 assign', array1, assign);
perf('100 reduce', array1, reduce);
perf('1000 assign', array2, assign);
perf('1000 reduce', array2, reduce);
perf('10000 assign', array3, assign);
perf('10000 reduce', array3, reduce);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment