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(Object.getPrototypeOf(firstObject), Object.getOwnPropertyDescriptors(firstObject));
const firstObject = {
sampleData: 'Hello world',
sampleMethod: () => { return true; }
};
const secondObject = Object.assign({}, firstObject);
Object.setPrototypeOf(secondObject, Object.getPrototypeOf(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 | 28109708.0 Ops/sec |
Test Object.create | 472043.8 Ops/sec |
Test Object.assign | 1667937.4 Ops/sec |
Let's break down the provided benchmark and its individual test cases.
Benchmark Overview
The benchmark compares three approaches to create a shallow copy of an object:
...
): Creates a new object with the same properties as the original object, without modifying it.Object.assign()
: Copies all enumerable own properties from one or more source objects to a target object.Object.create()
: Creates a new object that inherits properties from an existing object (the prototype).Options Compared
The benchmark tests each approach with the same input object:
const firstObject = {
sampleData: 'Hello world',
sampleMethod: () => { return true; }
};
The objective is to determine which approach is faster and more efficient.
Pros and Cons of Each Approach
...
):Object.assign()
for large objects or when dealing with complex property names.Object.assign()
:Object.create()
:Object.assign()
or spread operator due to the overhead of creating a new object and setting its prototype.Library/Functionality Used
None of the test cases explicitly use any third-party libraries. However, it's worth noting that some browsers may have internal optimizations for these functions that could affect their performance in certain scenarios.
Special JavaScript Features/Syntax
The benchmark uses modern JavaScript features, such as:
const { sampleData, sampleMethod } = firstObject;
)'\r\n \tsampleData: 'Hello world',\r\n\tsampleMethod: () => { return true; }\r\n;'
)These features are not specific to the benchmark itself but rather demonstrate the use of modern JavaScript in the test cases.
Other Alternatives
Other approaches to create a shallow copy of an object include:
JSON.parse(JSON.stringify(obj))
cloneDeep()
Keep in mind that these alternatives may have different performance characteristics and trade-offs compared to the methods tested in this benchmark.
The results from the benchmark show that the spread operator (...
) is the fastest approach, followed closely by Object.assign()
. Object.create()
is slower due to its overhead of creating a new object and setting its prototype.