var n = {foo: 'bar', hello: [{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'}]};
while(n.length < 1000) {
n = [n];
}
var n = {foo: 'bar', hello: [{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'}]};
n = JSON.stringify(n);
var j = JSON.parse(n)
var n = {foo: 'bar', hello: [{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'},{hello: 'world', foo: 'bar'}]};
while(n.length < 1000) {
n = Object.assign({}, n);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread operator | |
JSON Parse | |
Object.assign |
Test name | Executions per second |
---|---|
Spread operator | 18603810.0 Ops/sec |
JSON Parse | 342157.7 Ops/sec |
Object.assign | 23937398.0 Ops/sec |
Let's break down the provided benchmark and explain what is tested, the options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark tests three different approaches to create a new object reference:
Object.assign
method to create a shallow copy of an object....
) to create a deep copy of an object by converting it to a JSON string and then parsing it back into an object.JSON.stringify
and then parses it back into an object using JSON.parse
.Options Compared
The three options are compared in terms of their performance (executions per second) on a Windows Desktop with Firefox 79 browser.
Pros and Cons of Each Approach
Object.assign
, especially for large objects. The spread operator is also supported by most modern browsers, but its performance can vary depending on the browser and JavaScript engine.Object.assign
or the spread operator, especially for large objects.Other Considerations
Object.assign
, the spread operator, or JSON.Stringify/Parse
will allocate memory on the heap. The amount of memory allocated depends on the size and complexity of the original object.Library Used
None of the benchmark options use a specific library. However, JSON.stringify
and JSON.parse
rely on the JSON specification, which is maintained by the Internet Engineering Task Force (IETF).
Special JS Feature or Syntax
The spread operator (...
) was introduced in ECMAScript 2015 and has since become a widely supported feature across most modern browsers.
Benchmark Preparation Code and Test Cases
The benchmark preparation code is empty for all three test cases, indicating that the focus is solely on measuring the performance of each approach. The individual test cases provide different approaches to create a new object reference, with varying degrees of complexity:
The benchmark results show the executions per second for each browser, providing insight into the relative performance of each approach on this specific use case.