Skip to content

Commit 7e5f500

Browse files
committedMay 7, 2017
assert: improve deepEqual perf for large input
Use a Map instead of an array for checking previously found cyclic references. This reduces complexity for an array-of-objects case from O(n²) to O(n·log n). Fixes: #12842 PR-URL: #12849 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Jeremiah Senkpiel <[email protected]> Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: Rich Trott <[email protected]>
1 parent 3fd890a commit 7e5f500

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed
 

‎lib/assert.js

+15-6
Original file line numberDiff line numberDiff line change
@@ -285,15 +285,24 @@ function _deepEqual(actual, expected, strict, memos) {
285285
// Note: this accounts for both named and indexed properties on Arrays.
286286

287287
// Use memos to handle cycles.
288-
memos = memos || { actual: [], expected: [] };
289-
const actualIndex = memos.actual.indexOf(actual);
290-
if (actualIndex !== -1) {
291-
if (actualIndex === memos.expected.indexOf(expected)) {
288+
if (!memos) {
289+
memos = {
290+
actual: { map: new Map(), position: 0 },
291+
expected: { map: new Map(), position: 0 }
292+
};
293+
}
294+
295+
const actualPosition = memos.actual.map.get(actual);
296+
if (actualPosition !== undefined) {
297+
if (actualPosition === memos.expected.map.get(expected)) {
292298
return true;
293299
}
300+
} else {
301+
memos.actual.map.set(actual, memos.actual.position++);
302+
}
303+
if (!memos.expected.map.has(expected)) {
304+
memos.expected.map.set(expected, memos.expected.position++);
294305
}
295-
memos.actual.push(actual);
296-
memos.expected.push(expected);
297306

298307
return objEquiv(actual, expected, strict, memos);
299308
}

0 commit comments

Comments
 (0)