<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.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));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
angular.copy() | |
JSON.parse(JSON.stringify()) |
Test name | Executions per second |
---|---|
angular.copy() | 1614766.4 Ops/sec |
JSON.parse(JSON.stringify()) | 1036280.8 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Definition
The test is comparing two methods for copying an array of objects in JavaScript: angular.copy()
and JSON.parse(JSON.stringify())
.
What are these methods?
angular.copy()
: This method is part of the AngularJS library, which provides a way to safely copy objects without worrying about circular references or other issues that can arise when using shallow copies like slice()
, concat()
, etc.JSON.parse(JSON.stringify())
: This method uses the JSON stringification and parsing mechanisms in JavaScript to create a deep copy of an object.Pros and Cons
angular.copy()
:
JSON.parse(JSON.stringify())
:
angular.copy()
.Library and Syntax
In this benchmark, angular.copy()
is used in the script preparation code, while JSON.parse(JSON.stringify())
is used in another test case. The latter uses a library (JSON
) that provides the necessary functionality for creating a deep copy of an object.
There are no special JavaScript features or syntaxes being tested in this benchmark.
Other Alternatives
Besides the two methods mentioned above:
slice()
or concat()
to create a shallow copy, which is not as safe as the angular.copy()
method but can be faster.cloneDeep()
function: A popular utility library that provides a deep clone function, similar to JSON.parse(JSON.stringify())
.Object.assign()
and Array.prototype.slice()
in combination: A custom approach to create a deep copy by using Object.assign()
and Array.prototype.slice()
, which requires more manual handling.Keep in mind that the choice of method depends on the specific use case, performance requirements, and compatibility with different JavaScript environments.