const obj = {}
for (let i = 0; i < 10000; i++) {
Object.assign(obj, { i })
}
let obj = {}
for (let i = 0; i < 10000; i++) {
obj = { obj, { i } }
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
assign | |
spread |
Test name | Executions per second |
---|---|
assign | 8606.4 Ops/sec |
spread | 7010.5 Ops/sec |
Let's break down the benchmark and explain what is being tested.
The benchmark measures the performance of two methods for updating an object: Object.assign()
and the spread operator (...
). The test case creates an empty object, then uses a loop to add 10,000 properties with unique keys (the values are just numeric strings).
What's being compared?
Object.assign()
: This method takes two arguments: the target object and an array of key-value pairs. It merges the values into the target object....
): This operator creates a new object by taking all enumerable own properties from one or more source objects. In this case, it's used to create a new object with 10,000 properties (keys) set to unique values.Pros and Cons of each approach:
Object.assign()
: Pros:...
): Pros:Object.assign()
because it doesn't need to create a new object.Library/ Framework considerations:
There are no libraries or frameworks explicitly mentioned, but Object.assign()
has been a built-in method of the Object
prototype since ECMAScript 5 (2009), so it's widely supported. The spread operator (...
) is also a standard feature introduced in ECMAScript 2018+.
Special JS features:
There are no special JavaScript features or syntax mentioned in this benchmark, but if you're interested in learning more about the latest features and updates, I can provide information on that.
Alternatives:
If you want to test other approaches for updating objects, you could consider:
Array.prototype.map()
method with an object constructor, like so:const obj = {};
for (let i = 0; i < 10000; i++) {
obj[i] = {};
}
Or using a custom object creation function with a loop:
function createObject(keys) {
const obj = {};
for (let key of keys) {
obj[key] = {};
}
return obj;
}
const obj = [];
for (let i = 0; i < 10000; i++) {
obj.push(createObject([i]));
}
Keep in mind that these alternatives may have different performance characteristics than the Object.assign()
and spread operator approaches.
I hope this explanation helps you understand the benchmark!