// Object.assign
function createObject(fillValue) {
return Object.fromEntries(new Array(1024*12).fill(fillValue).map((value, index) => {
return [fillValue + index, fillValue + index];
}));
}
const params = createObject('params');
const other = Object.assign(createObject('assign'), params);
// spread operator
function createObject(fillValue) {
return Object.fromEntries(new Array(1024*12).fill(fillValue).map((value, index) => {
return [fillValue + index, fillValue + index];
}));
}
const params = createObject('params');
const other = {createObject('spread'), params};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
spread operator |
Test name | Executions per second |
---|---|
Object.assign | 40.6 Ops/sec |
spread operator | 31.4 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and the pros and cons of each approach.
Benchmark Overview
The benchmark compares two ways to create large objects in JavaScript: using the traditional Object.assign()
method and the new ES6 spread operator (...
).
Script Preparation Code
The script preparation code is not provided, but it's assumed that both test cases use the same underlying logic to generate a large object with 1024*12 properties.
For the "spread operator" test case, the code uses Object.fromEntries()
method, which is a part of the JavaScript standard library. This method creates an object from an array of key-value pairs.
Library Used:
In this case, the Object.fromEntries()
method is used as a helper function to generate the large object.
Test Cases
There are two test cases:
Object.assign()
method to create the large object....
) to create the large object.Pros and Cons of Each Approach
Object.assign()
:...
):Other Considerations
Object.assign()
due to its simpler syntax and lack of method call overhead.Alternatives
If you need to support older browsers (before Chrome 100), you may consider using other libraries or polyfills to implement the spread operator. Some alternatives include:
_.assign()
methodobject-assign
for compatibility with older browsersKeep in mind that if you're targeting modern browsers and want to take advantage of the spread operator, it's likely a better choice.
For those interested in learning more about JavaScript features or syntax, some notable mentions include:
Object.fromEntries()
: introduced in ECMAScript 2017....
spread operator: introduced in ECMAScript 2015 (ES6).These features have improved performance and readability in modern JavaScript development.