<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'];
window.equals = (a, b) =>
a.length === b.length &&
a.every((v, i) => v === b[i]);
window.equalsIgnoreOrder = (a, b) => {
if (a.length !== b.length) return false;
const uniqueValues = new Set([a, b]);
for (const v of uniqueValues) {
const aCount = a.filter(e => e === v).length;
const bCount = b.filter(e => e === v).length;
if (aCount !== bCount) return false;
}
return true;
}
_.isEqual(window.foo, window.bar)
JSON.stringify(window.foo) === JSON.stringify(window.bar);
window.equals(window.foo, window.bar)
window.equalsIgnoreOrder(window.foo, window.bar)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.isEqual | |
JSON.stringify | |
equals | |
equalsIgnoreOrder |
Test name | Executions per second |
---|---|
_.isEqual | 15618695.0 Ops/sec |
JSON.stringify | 8565059.0 Ops/sec |
equals | 116523576.0 Ops/sec |
equalsIgnoreOrder | 7431307.0 Ops/sec |
Let's break down the provided benchmark JSON and explore what's being tested.
Benchmark Definition
The benchmark compares three different methods to compare two arrays: lodash
's _isEqual
function, JSON.stringify
with equality check using ===
, and a custom equals
function implemented by the test user. The third method is an implementation of the "ignore order" approach for comparing arrays, which ignores the original order of elements when checking for equality.
Options Compared
JSON.stringify
and then compares these strings using the ===
operator. Since this approach converts the arrays to strings, it doesn't take into account any potential differences in element order or data type.false
. If an element is missing from one array compared to the other, it also returns false
.Pros and Cons
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, object creation, and more. The _isEqual
function in this benchmark is part of Lodash's MoreUtils
module, which provides functions for comparing objects and arrays.
Special JS Feature/ Syntax: None There are no special JavaScript features or syntaxes being used in this benchmark that would require additional explanation.
Other Alternatives
For comparing arrays, you can use other approaches like:
JSON.stringify + ===
approach but using the every()
method instead.These alternatives can provide different trade-offs between performance, complexity, and ease of implementation compared to the approaches tested in this benchmark.