Skip to content

Commit 8e1bdae

Browse files
committed
perf: improve Map performance with dedicated mapEqual function
1 parent 561c76f commit 8e1bdae

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

index.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,9 @@ function deepEqual(leftHandOperand, rightHandOperand, options) {
174174
case 'set':
175175
result = setEqual(leftHandOperand, rightHandOperand, options);
176176
break;
177+
case 'map':
178+
result = mapEqual(leftHandOperand, rightHandOperand, options);
179+
break;
177180
default:
178181
result = objectEqual(leftHandOperand, rightHandOperand, options);
179182
}
@@ -231,6 +234,43 @@ function setEqual(leftHandOperand, rightHandOperand, options) {
231234
return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options);
232235
}
233236

237+
/*!
238+
* Compare two maps by forEaching over them,
239+
* and comparing the resulting key/value pairs.
240+
*
241+
* Speed Optimization:
242+
* Pre:
243+
* map x 320,939 ops/sec ±1.45% (81 runs sampled)
244+
* map (complex) x 149,099 ops/sec ±1.55% (76 runs sampled)
245+
* map (differing) x 251,749 ops/sec ±7.59% (73 runs sampled)
246+
* Post:
247+
* map x 511,685 ops/sec ±1.70% (82 runs sampled)
248+
* map (complex) x 247,723 ops/sec ±1.42% (81 runs sampled)
249+
* map (differing) x 450,797 ops/sec ±1.74% (78 runs sampled)
250+
* @param {Set} a
251+
* @param {Set} b
252+
* @return {Boolean} result
253+
*/
254+
255+
function mapEqual(leftHandOperand, rightHandOperand, options) {
256+
if (leftHandOperand.size !== rightHandOperand.size) {
257+
return false;
258+
}
259+
var result = true;
260+
leftHandOperand.forEach(function traverseLHMap(lhoKey, lhoValue) {
261+
var found = false;
262+
rightHandOperand.forEach(function traverseRHMap(rhoKey, rhoValue) {
263+
if (deepEqual(lhoKey, rhoKey, options) && deepEqual(lhoValue, rhoValue, options)) {
264+
found = true;
265+
}
266+
});
267+
if (!found) {
268+
result = false;
269+
}
270+
});
271+
return result;
272+
}
273+
234274
/*!
235275
* Simple equality for flat iterable objects
236276
* such as Arrays, TypedArrays or Node.js buffers.

0 commit comments

Comments
 (0)