<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
window.foo = {a: false, b: '1', c: 3};
window.bar = {a: false, b: '1', c: 3};
_.isEqual(window.foo, window.bar)
JSON.stringify(window.foo) === JSON.stringify(window.bar);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
isEqu | |
json |
Test name | Executions per second |
---|---|
isEqu | 319681.9 Ops/sec |
json | 294034.9 Ops/sec |
I'd be happy to explain the provided benchmark.
What is tested?
The provided benchmark measures the performance difference between two approaches: _.isEqual
from the Lodash library and a simple string comparison using JSON.stringify
. The test creates two objects, window.foo
and window.bar
, with identical properties but different types (number vs. string). It then checks if these two objects are equal using both methods.
Options compared
There are two options being compared:
JSON.stringify
function converts both objects into strings and then compares them.Pros and Cons
Library
The Lodash library is a popular utility library for JavaScript that provides a wide range of functions for tasks such as string manipulation, array operations, and object comparison. In this benchmark, _.isEqual
is used to compare two objects efficiently.
Special JS feature or syntax
There are no special JS features or syntax being tested in this benchmark. The focus is on comparing the performance of two different approaches to equality checking.
Other alternatives
If you wanted to implement a custom equality checker without relying on Lodash, you could use a simple recursive function that compares each property of the objects:
function equal(a, b) {
if (typeof a !== typeof b) return false;
for (let key in a) {
if (a[key] !== b[key]) return false;
}
return true;
}
Another approach could be to use the Object.keys
method to compare the properties of the objects:
function equal(a, b) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (let i = 0; i < keysA.length; i++) {
if (a[keysA[i]] !== b[keysB[i]]) return false;
}
return true;
}
Keep in mind that these custom implementations may not be as efficient or reliable as using a well-tested library like Lodash.