<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.6/angular.min.js"></script>
</head>
<body>
</body>
</html>
var origObj = {
Object: { Name: "Object1", Desc: "Desc2" },
Object2: { Name: "Object2", Desc: "Desc2" },
Array1: [ "item2", "xitem2", "item3", "item1", "item2", "itexm6", "item1", "item7", "itesm1" ],
Array2: [ "itexm1", "item3", "item1", "istem9", "item2", "item1", "itemx8", "ites1", "itesm1" ],
Array3: [ "item3", "itesm1", "item7", "item1", "itexm1", "item33", "ixtem1", "itesm1", "itezm0" ],
};
var newObj = {};
newObj = angular.copy(origObj);
newObj = JSON.parse(JSON.stringify(origObj));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
angular.copy() | |
JSON.parse(JSON.stringify()) |
Test name | Executions per second |
---|---|
angular.copy() | 489070.6 Ops/sec |
JSON.parse(JSON.stringify()) | 238913.4 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition
The benchmark measures the performance of two approaches for copying an object in JavaScript: angular.copy()
and JSON.parse(JSON.stringify())
.
Options being compared
Two options are being compared:
JSON.stringify()
method to serialize the object and then parses the resulting string back into an object.Pros and Cons
JSON
object.angular.copy()
, especially for large objects.Library usage
The benchmark uses the AngularJS library, specifically the angular.copy()
function. The purpose of this library is to provide a set of tools and features for building web applications, including DOM manipulation, data binding, and dependency injection.
Special JS feature or syntax
There are no special JavaScript features or syntaxes being tested in this benchmark. However, it's worth noting that the use of JSON.parse(JSON.stringify())
relies on the fact that JSON strings can be parsed back into objects using the JSON
object.
Other alternatives
If you wanted to implement your own copy function without using a dedicated library like AngularJS, you could consider the following alternatives:
{...obj}
): This is a modern JavaScript feature introduced in ECMAScript 2018. It allows you to create a shallow copy of an object by spreading its properties into a new object.Object.assign()
: This method creates a shallow copy of an object by assigning its properties to a new object.Array.prototype.slice()
and Object.keys()
: You can use these methods in combination to create a deep copy of an array-like object.Each of these alternatives has its own trade-offs and may be more suitable for specific use cases or performance requirements.