New Object from Reduce vs. ForEach vs. Reduce vs. Reduce w. Object.assign

Benchmark created on


Description

Setup

var objects = Array.from(new Array(1000)).map((r, i) => ({
    id: `id-${i}`,
    val: i
}));
// Output should be
// { "id-0": 0, "id-1": 1, ... }

Test runner

Ready to run.

Testing in
TestOps/sec
Populate object via ForEach
var newMapFE = {};
objects.forEach(o => { newMapFE[o.id] = o.val })
ready
Populate new object via Reduce
objects.reduce((acc, item) => ({...acc, [item.id]: item.val}), {});
ready
Populate same object via Reduce (don't use ..., that's just silly)
objects.reduce((acc, item) => { acc[item.id] = item.val; return acc }, {});
ready
Let's try Object.assign, since we're here anyway
objects.reduce((acc, item) => { Object.assign(acc, { [item.id]: item.val }); return acc }, {});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.