for (i = 0; i < 10; i++) {}
const firstObject = {
sampleData: 'Hello world',
sampleMethod: () => { return true; }
};
const secondObject = {firstObject};
const firstObject = {
sampleData: 'Hello world',
sampleMethod: () => { return true; }
};
const secondObject = Object.create(firstObject);
const firstObject = {
sampleData: 'Hello world',
sampleMethod: () => { return true; }
};
const secondObject = Object.assign({}, firstObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Test Spread operator | |
Test Object.create | |
Test Object.assign |
Test name | Executions per second |
---|---|
Test Spread operator | 15832545.0 Ops/sec |
Test Object.create | 1730335.1 Ops/sec |
Test Object.assign | 22896494.0 Ops/sec |
What is being tested?
The provided JSON represents a JavaScript microbenchmark, specifically testing the performance of three methods to create a shallow copy of an object:
...
): This method creates a new object by spreading the properties of another object.The benchmark measures which approach is faster in terms of execution per second for each test case.
Options comparison
The main options being compared are:
...
): Creates a new object by spreading the properties of another object.{ property: value }
syntax.Object.assign()
method's signature.Object.assign()
, as it allows you to set any property on the new object, not just those specified in the original object.Object.assign()
.Library usage
In this benchmark, none of the libraries are explicitly mentioned. However, it is worth noting that both Object.assign()
and Object.create()
rely on the JavaScript prototype chain, which is a fundamental concept in JavaScript.
Special JS feature or syntax
The spread operator (...
) was introduced in ECMAScript 2015 (ES6) as a new way to create objects from existing objects. It has become a popular and efficient method for creating shallow copies of objects.
In the provided benchmark, the spread operator is used in the following test case:
const firstObject = { \r\n \tsampleData: 'Hello world',\r\n\tsampleMethod: () => { return true; }\r\n};\r\nconst secondObject = {...firstObject};
Alternatives
Other alternatives for creating shallow copies of objects in JavaScript include:
JSON.parse(JSON.stringify(obj))
method, which can create a deep copy of an object by serializing it as JSON and then parsing it back into an object.cloneDeep()
function for creating deep copies of objects.However, these alternatives are generally slower and more memory-intensive than the methods being tested in this benchmark.