var theJSON = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}
var result = {theJSON}
var theJSON = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}
var result = JSON.parse(JSON.stringify(theJSON))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
JSON Parse & Stringify |
Test name | Executions per second |
---|---|
Spread | 6352603.0 Ops/sec |
JSON Parse & Stringify | 256058.0 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance difference between two approaches: using the spread operator (...
) to create a shallow copy of an object, and using JSON.parse(JSON.stringify())
to create a deep copy of an object.
Options Compared
Two options are compared:
Pros and Cons
Library/Functionality Used
In this benchmark, JSON.parse(JSON.stringify())
is used from the built-in JavaScript JSON
object. This function is a standard part of the language and does not require any external libraries or dependencies.
Special JS Feature/Syntax
There are no special JS features or syntax used in this benchmark other than the use of the spread operator (...
) and the JSON.parse(JSON.stringify())
method.
Other Alternatives
If you need to create a deep copy of an object, you can also use libraries like Lodash's cloneDeep()
function or a recursive function that clones all properties of an object. However, these alternatives are not part of the standard JavaScript language and require additional dependencies.
In summary, this benchmark measures the performance difference between two approaches for creating shallow copies of objects: using the spread operator (...
) versus using JSON.parse(JSON.stringify())
. The choice of approach depends on your specific use case and whether you need a deep copy of an object.