const finalObject = Object.assign({}, document.body);
const finalObject = {document.body};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using Object.assign | |
Using the spread operator |
Test name | Executions per second |
---|---|
Using Object.assign | 57280848.0 Ops/sec |
Using the spread operator | 59599672.0 Ops/sec |
Let's dive into the world of JavaScript benchmarking.
What is being tested?
The provided JSON represents a benchmark test comparing the performance of two methods to create a shallow copy of an object: Object.assign()
and the spread operator (...
). The test is designed to measure which method is faster in creating a copy of the HTML body element.
Options compared
There are only two options being compared:
...
): This operator creates a new object with the same keys and values as an existing object.Pros and Cons of each approach
Object.assign():
Pros:
Array.prototype.slice()
method to create a copy)Cons:
Spread Operator (...
):
Pros:
Cons:
Other considerations
The spread operator is a relatively new feature introduced in ECMAScript 2018. It's faster and more concise than Object.assign() but only works in modern browsers.
If you need to support older browsers, you may want to use Object.assign() or implement a polyfill for the spread operator.
Libraries used
There isn't a specific library mentioned in the benchmark definition, but it's likely that the test uses a library like jsdom
to create a mock HTML document and simulate browser behavior.
Special JS feature or syntax
The spread operator (...
) is a new feature introduced in ECMAScript 2018. It allows you to create a new object by copying the keys and values from an existing object using the syntax const newObject = { ... existingObject };
.
Benchmark preparation code
The script preparation code for each test case is empty, which means that the benchmarking tool will generate the test cases automatically.
Individual test cases
There are two test cases:
Object.assign({}, document.body);
.{...document.body};
.The benchmarking tool runs each test case multiple times and measures the average execution time per second.
Latest benchmark result
The latest benchmark result shows that the spread operator is faster than Object.assign() in creating a shallow copy of the HTML body element, with an average execution time of 4348657.5 executions per second compared to 2265812.25 executions per second for Object.assign().