<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function forEach(array, iteratee) {
let index = -1;
const length = array.length;
while (++index < length) {
iteratee(array[index], index);
}
return array;
}
function clone(target, map = new WeakMap()) {
if (typeof target === 'object') {
const isArray = Array.isArray(target);
let cloneTarget = isArray ? [] : {};
if (map.get(target)) {
return map.get(target);
}
map.set(target, cloneTarget);
if (isArray) {
forEach(target, (value, index) => {
cloneTarget[index] = value;
})
} else {
forEach(Object.keys(target), (key, index) => {
cloneTarget[key] = target[key];
})
}
return cloneTarget;
} else {
return target;
}
}
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;
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = clone(MyObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone | |
Bitfish Simple Clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 368755.3 Ops/sec |
Json clone | 210961.0 Ops/sec |
Bitfish Simple Clone | 526333.8 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three different approaches to cloning an object: Lodash cloneDeep
, JSON Clone
, and Bitfish Simple Clone
. The cloned objects are created using the original MyObject
definition, which includes various data types such as numbers, booleans, and nested objects.
Cloning Approaches
cloneDeep
function creates a deep copy of an object, which means it recursively clones all nested properties.JSON.parse(JSON.stringify(obj))
method to create a clone of the input object. While this works for simple objects, it can lead to issues when dealing with complex data structures or functions as values.clone
function provided in the benchmark definition creates a shallow copy of an object, which means only the top-level properties are cloned, and nested properties are referenced.Pros and Cons
Library and Special JS Features
Other Considerations
MyObject
definition, which is easy to understand and clone. Real-world scenarios may require more complex data structures or handling specific edge cases.Alternatives
If you're looking for alternative cloning libraries or approaches, consider:
Keep in mind that each alternative has its pros and cons, and you should evaluate them based on your specific use case and requirements.