<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
const obj1 = {
boolVal: true,
arrVal: [
"string 1",
"string 2",
"string 3",
"string 4",
"string 5",
"string 6",
"string 7",
]
};
const obj2 = {
boolVal: true,
arrVal: [
"string 1",
"string 2",
"string 3",
"string 4",
"string 5",
"string 6",
"string 7",
]
};
_.isEqual(obj1, obj2);
JSON.stringify(obj1) === JSON.stringify(obj2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.isEqual | |
JSON.stringify |
Test name | Executions per second |
---|---|
_.isEqual | 2734971.0 Ops/sec |
JSON.stringify | 2695942.0 Ops/sec |
The benchmark being tested compares two methods of deep equality checking in JavaScript: using the lodash
library's _.isEqual
method versus using the built-in JSON.stringify
method for comparison.
_.isEqual
Method (from Lodash)
lodash
library performs a deep comparison between two values to determine if they are equivalent. Lodash handles various data types and checks for structural equality rather than just reference equality.JSON.stringify
Method
_.isEqual
:NaN
, functions, and cyclic references._.isEqual
:lodash
library, which adds external dependencies to the project.JSON.stringify
:JSON.stringify
:undefined
, Symbol
, etc.) correctly, leading to incorrect comparisons for complex objects.From the benchmark results provided, we see that JSON.stringify
has a higher execution count, with 2,933,073 executions per second compared to _.isEqual
, which achieved 2,605,226 executions per second. This indicates that JSON.stringify
is generally faster in scenarios with non-complex structures, while _.isEqual
provides a more thorough and safer way to perform equality checks for complex data.
===
operator: This only checks for reference equality, not structure.deep-equal
or fast-deep-equal
that are designed specifically for performance-sensitive deep equality checks.In conclusion, while both methods have their advantages and trade-offs, the choice between them should be guided by the specific requirements of the application, such as data complexity, performance needs, and tolerance for external dependencies.