Copying data 2; mapping vs. spreading then modifying vs. Object.assign then modifiying
Date tested:
one year ago
User agent:
Mozilla/5.0 (Linux; Android 12; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Mobile Safari/537.36
Test name
Executions per second
Mapping
541263.8 Ops/sec
spreading, then modifying
650415.3 Ops/sec
Object.assign, then modifying
159075.0 Ops/sec
Benchmark definition (click to collapse):
Script Preparation code:
var data = [{ foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } }, { foo: { bar: { baz: "hi" } } } ];
Tests:
Mapping
data.map((d, i) => i === 2 ? ({...d, bar: { baz: "bye" } }) : d)
spreading, then modifying
const copy = [...data]; copy[2] = { ...copy[2], bar: { baz: "bye" } };
Object.assign, then modifying
const copy = Object.assign([], data) copy[2] = { ...copy[2], bar: { baz: "bye" } };
Open this result on MeasureThat.net