var bigdata = {};
for (var i = 0; i < 100; i++) {
var usdata = {
name: 'user' + i,
surname: 'user' + i,
friends: {}
};
for (var j = 0; j < 10; j++) {
usdata.friends['friend' + j] = {
_ref: 'firend' + j
};
}
bigdata['user' + i] = usdata;
}
function lazyExtend(prev, next) {
if (!prev) return;
for (var k in next) {
var val = next[k];
if (typeof(val) !== 'object') continue;
lazyExtend(prev[k], val);
}
if (!next.toJSON) next.toJSON = jsonAll;
Object.setPrototypeOf(next,prev);
}
function jsonAll() {
var tmp = {};
for(var key in this) {
var to = typeof this[key];
if(to !== 'function')
tmp[key] = this[key];
}
return tmp;
}
var copy = JSON.parse(JSON.stringify(bigdata.user0));
var copy = {};
lazyExtend(bigdata.user0,copy);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON rw | |
Prototype |
Test name | Executions per second |
---|---|
JSON rw | 134600.4 Ops/sec |
Prototype | 1611371.9 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark definition.
Main Objective: The primary objective is to compare two approaches for creating copies of objects in JavaScript:
JSON Rewriting (JSON rw):
In this approach, a deep copy of the object bigdata.user0
is created using the JSON.parse(JSON.stringify())
method. This method serializes the object to a JSON string, and then deserializes it back into an object. The resulting object is not the original object, but rather a new object that represents the same data.
Prototype Chain Extension (Prototype):
In this approach, the lazyExtend
function is used to extend the prototype chain of an object (bigdata.user0
). The lazyExtend
function recursively copies the properties from one object (prev
) to another object (next
). This creates a new object that inherits from the original object's prototype.
Comparison:
The benchmark aims to compare the performance of these two approaches. In practice, both methods have their pros and cons:
lazyExtend
functionLibrary Used:
The JSON.parse(JSON.stringify())
method is a built-in JavaScript function that uses a custom implementation to serialize and deserialize objects. The lazyExtend
function is defined in the provided code.
Other Considerations:
Alternatives:
Some alternative approaches for creating copies of objects in JavaScript include:
Object.assign()
method (available in modern browsers)cloneDeep()
function