<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var MyObject = {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 123456789,
myBoolean: true,
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...'
}
};
var myCopy = null;
function recursiveDeepCopy(o) {
var newO,
i;
if (typeof o !== 'object') {
return o;
}
if (!o) {
return o;
}
if ('[object Array]' === Object.prototype.toString.apply(o)) {
newO = [];
for (i = 0; i < o.length; i += 1) {
newO[i] = recursiveDeepCopy(o[i]);
}
return newO;
}
newO = {};
for (i in o) {
if (o.hasOwnProperty(i)) {
newO[i] = recursiveDeepCopy(o[i]);
}
}
return newO;
}
function recursiveDeepCopyTTTeam(o) {
let newO;
let i;
if (typeof o !== 'object') {
return o;
}
if (!o) {
return o;
}
if (Object.prototype.toString.apply(o) === '[object Array]') {
newO = [];
for (i = 0; i < o.length; i += 1) {
newO[i] = recursiveDeepCopy(o[i]);
}
return newO;
}
newO = {};
Object.keys(o).forEach((key) => {
newO[key] = recursiveDeepCopy(o[key]);
});
return newO;
}
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = recursiveDeepCopy(MyObject);
myCopy = recursiveDeepCopyTTTeam(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Loadash | |
JSON Parse | |
recursiveDeepCopy | |
recursiveDeepCopyTTTeam |
Test name | Executions per second |
---|---|
Loadash | 771005.4 Ops/sec |
JSON Parse | 629910.2 Ops/sec |
recursiveDeepCopy | 4512344.5 Ops/sec |
recursiveDeepCopyTTTeam | 2783028.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition JSON
The provided JSON represents a benchmark definition, which includes:
MyObject
with various properties and methods.Individual Test Cases
Each test case represents a separate benchmark that tests different approaches for creating a deep copy of the MyObject
object:
lodash.cloneDeep
function from the Lodash library to create a deep copy of the MyObject
.MyObject
using the JSON.parse()
method.recursiveDeepCopy
, to create a deep copy of the MyObject
.Comparison of Approaches
Let's compare the four approaches:
Other Considerations
When choosing an approach, consider factors such as:
Alternatives
If you're looking for alternative approaches, consider:
JSON5
or json-stringify-safe
for JSON serialization/deserialization.Immer
or ramda
.Keep in mind that each approach has its strengths and weaknesses, and the best choice depends on your specific use case and requirements.