<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
var obj = {
a: 1,
b: { c: 2 },
d: [4, 5, 6],
e: { f: [1, 2], g: { h: 1 } }
};
JSON.parse(JSON.stringify(obj))
$.extend(true, {}, obj);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
json | |
jquery |
Test name | Executions per second |
---|---|
json | 180178.6 Ops/sec |
jquery | 84045.8 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, and considered.
Benchmark Overview
The benchmark compares two approaches to create a deep clone of a JSON object: using JSON.parse(JSON.stringify(obj))
(the "json" approach) and using jQuery's $().extend(true, {}, obj)
method (the "jquery" approach).
Options Compared
Two options are compared:
JSON.parse(JSON.stringify(obj))
: This method uses the JSON.stringify()
function to serialize the JSON object into a string, which is then parsed again using JSON.parse()
to create a deep clone.$().extend(true, {}, obj)
: This method uses jQuery's $()
function to select an empty DOM element (which is not actually necessary in this case), and then passes the original object as an argument to the $.extend()
method. The second argument to $.extend()
creates a new object that will receive the properties of the original object, effectively creating a deep clone.Pros and Cons
Deep Clone Using JSON.parse(JSON.stringify(obj))
:
Pros:
Cons:
Deep Clone Using jQuery's $().extend(true, {}, obj)
:
Pros:
JSON.parse(JSON.stringify(obj))
approachCons:
JSON.parse(JSON.stringify(obj))
approachLibrary Usage
The benchmark uses the jQuery library, which is a popular JavaScript library for DOM manipulation and event handling. In this specific case, jQuery's $().extend(true, {}, obj)
method is used to create a deep clone of the JSON object.
Special JS Feature or Syntax
This benchmark does not use any special JavaScript features or syntax beyond what is required to execute the two cloning approaches.