<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
window.isEqualStringify = (obj1, obj2) => JSON.stringify(obj1) === JSON.stringify(obj2);
window.isEqualLodash = _.isEqual;
window.test1 = {
obj: {},
arr: [],
};
for (let i = 0; i < 1000; i++) {
test1.obj['prop_' + i] = {};
let arrReference = [];
test1.arr.push(arrReference);
let objReference = test1.obj['prop_' + i];
for (let j = 0; j < i; j++) {
objReference['internal_prop_' + j] = {};
objReference = objReference['internal_prop_' + j];
arrReference.push(j);
}
}
window.test2 = JSON.parse(JSON.stringify(test1));
isEqualStringify(test1, test2)
isEqualLodash(test1, test2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.stringify | |
lodash.isEqual |
Test name | Executions per second |
---|---|
JSON.stringify | 2.8 Ops/sec |
lodash.isEqual | 1.2 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark compares two methods for comparing objects: JSON.stringify
and lodash.isEqual
.
Options Compared
There are two options being compared:
JSON.stringify()
. This approach has the following pros and cons:JSON.stringify
due to the recursive nature of the comparisonLibrary: lodash
The lodash.isEqual
function is part of the Lodash library. Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, object creation, and string manipulation.
In this benchmark, the lodash.isEqual
function is used to compare two objects recursively, ensuring that all properties, including nested objects and arrays, are taken into account during the comparison.
Other Considerations
When choosing between these two approaches, consider the following:
lodash.isEqual
.JSON.stringify
.Alternatives
Other alternatives for comparing objects include:
toString()
method on an object's prototype chain to get a string representation of the object.However, these alternatives are generally less reliable and more error-prone than using a dedicated equality function like lodash.isEqual
or implementing your own deep equality check using JSON.stringify
.