<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
</head>
<body>
</body>
</html>
var origArr = [
{
name : "obj1",
val : 1,
color : "blue"
},
{
name : "obj2",
val : 2,
color : "red"
},
{
name : "obj3",
val : 3,
color : "green"
},
{
name : "obj4",
val : 4,
color : "orange"
}
];
var newArr = [];
newArr = angular.copy(origArr);
newArr = JSON.parse(JSON.stringify(origArr));
newArr = _.cloneDeep(origArr);
newArr = angular.fromJson(angular.toJson(origArr));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
angular.copy() | |
JSON.parse(JSON.stringify()) | |
_.colneDeep() | |
angular.fromJson(angular.toJson()) |
Test name | Executions per second |
---|---|
angular.copy() | 474922.6 Ops/sec |
JSON.parse(JSON.stringify()) | 290349.8 Ops/sec |
_.colneDeep() | 285128.5 Ops/sec |
angular.fromJson(angular.toJson()) | 189181.5 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare the performance of three methods for copying an array of objects:
angular.copy()
JSON.parse(JSON.stringify())
_.cloneDeep()
(using Lodash library)angular.fromJson(angular.toJson())
The goal is to determine which method provides a shallow copy, where the original object is not modified when the new copy is created.
Options Compared
Each option is compared in terms of its performance, specifically:
Pros and Cons of Each Approach:
fromJson
function to create a deep copy of the array by serializing it to JSON and then deserializing it back into an object.Special JS Feature or Syntax
None of the options explicitly use special JavaScript features or syntax. However, _.cloneDeep()
uses the Lodash library's internal implementation, which might involve some low-level optimizations not immediately apparent to JavaScript developers.
Other Considerations
angular.copy()
method is likely implemented in a way that takes advantage of the browser's internal object implementation, which might affect its performance compared to other methods.Alternatives
Other alternatives for creating deep copies of objects include:
for...in
loop to iterate over each property and create a new object with the same properties can achieve similar results as the methods tested in this benchmark....
) with Object.assign()
can also be used to create shallow copies of objects, but may not handle nested objects correctly.Keep in mind that each alternative has its own trade-offs in terms of performance, complexity, and additional dependencies required.