<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<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...'
},
createdAt: new Date(),
arr: [
1,
2,
3,
4,
5,
6,
7
]
};
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = angular.copy(MyObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone | |
Angular copy |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 273218.6 Ops/sec |
Json clone | 178522.2 Ops/sec |
Angular copy | 203089.6 Ops/sec |
Let's dive into the explanation of the provided benchmark.
The benchmark is designed to compare the performance of three different libraries: Lodash, AngularJS, and JSON Clone (v1.1). Each library is tested for its cloning functionality on a specific JavaScript object (MyObject
).
_.cloneDeep()
is used to create a deep copy of an object.angular.copy()
.The benchmark consists of three test cases:
myCopy = _.cloneDeep(MyObject);
MyObject
using Lodash's _.cloneDeep()
function.myCopy = angular.copy(MyObject);
MyObject
using AngularJS's angular.copy()
function.myCopy = JSON.parse(JSON.stringify(MyObject));
MyObject
using the JSON.parse()
and JSON.stringify()
methods.While these three libraries are popular choices for cloning functionality, there are other alternatives:
Object.assign()
: A more modern approach to copying objects using the Object.assign()
method.lodash-es
: An alternative implementation of Lodash that provides similar functionality without the polyfills required by lodash
.In conclusion, the benchmark highlights the performance differences between these three libraries when it comes to creating deep copies of JavaScript objects. The choice of library ultimately depends on the specific use case, project requirements, and personal preference.