<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
window.foo = {a:'cat', b:'dog', c:'bird'};
window.bar = {a:'cat', b:'dog', c:'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 | 800267.9 Ops/sec |
JSON.stringify | 693607.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Overview
The benchmark compares the performance of two approaches: using Lodash's isEqual
function versus manually comparing two objects using JSON.stringify
.
What is being compared?
The test case "_.isEqual" measures how fast Lodash's isEqual
function compares two shallow objects (window.foo
and window.bar
). The objects have string values for their properties.
On the other hand, the test case "JSON.stringify" checks how fast manually comparing the two objects using JSON.stringify
returns equal results. This approach converts both objects to strings and then compares them using the ===
operator.
Options compared
JSON.stringify
and then compares the resulting strings using the ===
operator.Pros and Cons of each approach
isEqual
, as it only compares property values using ===
.Other considerations
isEqual
function, which is a popular utility library for JavaScript.Alternatives
If you wanted to compare these approaches without using Lodash, you could:
isEqual
using only built-in JavaScript methods and data structures (e.g., Object.keys()
, Array.prototype.every()
).lodash-es
or fast-json-stable-stringify-compare
.JSON.stringify
, e.g., by using a recursive function to compare property values.Keep in mind that these alternatives may have different trade-offs in terms of performance, accuracy, and simplicity.