Member-only story

5x Faster Object.assign — A JavaScript Performance Trick

ohdarling
3 min readNov 11, 2024

--

JavaScript performance optimization is a crucial aspect of modern web development. One common task in JavaScript is copying properties from one object to another. The Object.assign() method is frequently used for this purpose. However, there are ways to achieve this task more efficiently. In this article, we'll explore how to make property copying up to 5 times faster than Object.assign().

Generate Test Objects

The test code here is used to generate the data for testing, which consists of 50 test objects each having 50 properties. This scenario is similar to what we encounter in our web app when receiving stock market data, where an object may contain numerous properties such as high, low, open, close, etc.

const HugeObjects = [];
for (let i = 0; i < 50; i++) {
let obj = {};
for (let j = 0; j < 50; j++) {
obj[`key${j}`] = Math.random();
}
HugeObjects.push(obj);
}

Test Cases

Test 1: Use Object.assign

This is a common usage method, where the object to be cloned is assigned to an empty object using Object.assign to achieve copying.

{
name: "object-assign",
test: (count) => {
const ret = [];
for (i = 0; i < count; ++i) {
let a = Object.assign({}, HugeObjects[Math.floor(Math.random() * 50) % 50]);
ret.push(a);
}
},
}

--

--

ohdarling
ohdarling

Written by ohdarling

Coding and creating, build apps on tickplant.com.

No responses yet