From e842bec025b5371e07e998f499cbaf8e6132f14a Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Sat, 27 Feb 2016 18:35:18 -0800 Subject: [PATCH] Optimize `_.intersection` to stop search once it matches the size of its smallest array. --- lodash.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lodash.js b/lodash.js index a3fbc1a0d..46e8ef31e 100644 --- a/lodash.js +++ b/lodash.js @@ -2769,6 +2769,7 @@ othLength = arrays.length, othIndex = othLength, caches = Array(othLength), + maxLength = Infinity, result = []; while (othIndex--) { @@ -2776,18 +2777,20 @@ if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } - caches[othIndex] = !comparator && (iteratee || array.length >= 120) + var length = array.length; + maxLength = length < maxLength ? length : maxLength; + caches[othIndex] = !comparator && (iteratee || length >= 120) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; + length = array.length; var index = -1, - length = array.length, seen = caches[0]; outer: - while (++index < length) { + while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; @@ -2795,7 +2798,7 @@ ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { - var othIndex = othLength; + othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache