<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.stringBar = JSON.stringify(window.bar);
_.isEqual(window.foo, window.bar)
JSON.stringify(window.foo) === window.stringBar
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.isEqual | |
JSON.stringify |
Test name | Executions per second |
---|---|
_.isEqual | 2237999.5 Ops/sec |
JSON.stringify | 1964443.1 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for testing equality between two arrays: Lodash's isEqual
function and JSON string comparison using JSON.stringify
.
Test Cases
There are two test cases:
isEqual
function: This test case creates two identical arrays, window.foo
, and tests if Lodash's isEqual
function returns true
.window.foo
, converts it to a JSON string using JSON.stringify
, and then compares the resulting string with another identical array stored in window.stringBar
. The goal is to see if the two values are equal.Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, object transformation, and functional programming. In this case, Lodash's isEqual
function is used to compare arrays.
Pros of using Lodash:
Cons of using Lodash:
JSON String Comparison
The JSON string comparison test case uses the fact that in most programming languages, including JavaScript, two identical values are considered equal if and only if their string representations are equal. By converting an array to a JSON string using JSON.stringify
, we can compare it with another value.
Pros of JSON string comparison:
Cons of JSON string comparison:
JSON.stringify
can be slow for big objects.Other Considerations
When comparing array equality using Lodash's isEqual
function, keep in mind that it also checks for:
If you only care about the presence and value of elements, you can use the $eq
function from Lodash.
For JSON string comparison, be aware that this approach may not work correctly if the arrays contain non-JSON data types (e.g., objects with circular references).
Other Alternatives
If you need to compare arrays efficiently without using a library like Lodash:
arrays-equal
function: A lightweight and efficient alternative to Lodash's isEqual
.Keep in mind that these alternatives may not be as widely supported or optimized as Lodash's implementation.