<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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.isEqual | |
JSON.stringify |
Test name | Executions per second |
---|---|
_.isEqual | 14464545.0 Ops/sec |
JSON.stringify | 7059659.5 Ops/sec |
Let's dive into the explanation.
The provided JSON represents a JavaScript microbenchmark on MeasureThat.net, which compares the performance of two approaches for shallow array equality comparison: using Lodash's isEqual
function and comparing JSON strings.
Lodash's isEqual
function
Lodash is a popular JavaScript utility library that provides various functions to perform common tasks. In this case, isEqual
is used to compare two values for deep equality.
Pros of using Lodash's isEqual
:
isEqual
handles complex data structures and recursive objects.Cons of using Lodash's isEqual
:
Comparing JSON strings
The alternative approach is to compare JSON strings using the ===
operator or JSON.stringify()
with no arguments.
Pros of comparing JSON strings:
Cons of comparing JSON strings:
Comparison options
The benchmark compares the performance of these two approaches:
_.isEqual(window.foo, window.bar)
JSON.stringify(window.foo) === JSON.stringify(window.bar)
These options are compared because they represent common patterns in JavaScript development: using external libraries for utility functions versus implementing custom comparisons.
Special considerations
In this benchmark, no special JavaScript features or syntax (e.g., async/await, promises) is used. However, it's essential to note that some modern browsers might have optimizations or quirks related to these features that could affect the benchmark results.
Alternatives
Other alternatives for shallow array equality comparison include:
Array.prototype.every()
with a custom comparison function.However, these alternatives might not be as widely supported or optimized for performance as Lodash's isEqual
or the built-in ===
operator.
The benchmark results show that Lodash's isEqual
is generally faster than comparing JSON strings, likely due to its optimized implementation and handling of complex data structures.