<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
window.foo = ['cat', 'dog', 'bird'];
window.bar = ['cat', 'dog', 'bird'];
_.isEqual(window.foo, window.bar)
JSON.stringify(window.foo) === JSON.stringify(window.bar);
window.foo === window.bar
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.isEqual | |
JSON.stringify | |
=== |
Test name | Executions per second |
---|---|
_.isEqual | 1760576.8 Ops/sec |
JSON.stringify | 1289858.4 Ops/sec |
=== | 4129818.2 Ops/sec |
The benchmark you're examining compares three different methods for checking equality between two shallow arrays of strings: _.isEqual
from the Lodash library, equality using JSON.stringify
, and strict equality using ===
. Each method has its own advantages and disadvantages.
_.isEqual
Understanding: Lodash is a popular JavaScript utility library that provides various functions for common programming tasks. The _.isEqual
function specifically checks for deep equality, which means it compares values recursively.
Pros:
Cons:
JSON.stringify
Equality CheckUnderstanding: This method converts both arrays to JSON strings and then compares the resulting strings using strict equality (===
).
Pros:
Cons:
JSON.stringify
can be slower than direct comparisons, especially for large arrays or complex objects, as it has to traverse the entire structure to convert it to a string.===
)Understanding: This operator checks whether the two references point to the same instance in memory.
Pros:
Cons:
The results indicate performance in terms of executions per second for each method when tested in Safari 18 on macOS.
===
: ~11.18 million executions per second_.isEqual
: ~5.63 million executions per secondJSON.stringify
: ~4.22 million executions per secondThe results strongly demonstrate that the strict equality operator ===
outperforms both Lodash's _.isEqual
and the JSON.stringify
method, making it the best choice for performance-critical situations when comparing shallow arrays of primitive types.
Array.prototype.every()
: Another modern JavaScript alternative would be to use methods like every
, which allows for a functional approach to equality checks. This would be faster than JSON.stringify
for shallow comparisons.In summary, the choice of method depends on the context: if performance is critical and you are only comparing shallow arrays, use ===
. If you need deep object comparisons, use _.isEqual
, keeping in mind the performance implications. For simple or temporary needs, JSON.stringify
offers a quick and easy way to check equality for non-complex data structures.