From b0b7b05847507aafafc955940099bf45daf0e90d Mon Sep 17 00:00:00 2001 From: Benedikt Meurer Date: Wed, 29 Nov 2017 10:44:08 +0100 Subject: [PATCH] Avoid repeated String#slice calls in stringDistance. The `stringDistance` function calls ```js strA.slice(0, -1) ``` and ```js strB.slice(0, -1) ``` multiple times, which is a bit of a waste of time here. JavaScript engines cannot generally eliminate the duplicated calls easily, so it's better to avoid the redundant calls altogether. This improves the chai test on the [web-tooling-benchmark](https://github.com/v8/web-tooling-benchmark) by around 8% when run with upcoming V8 6.4. --- lib/chai/utils/proxify.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/chai/utils/proxify.js b/lib/chai/utils/proxify.js index fd986d015..51e0e63e7 100644 --- a/lib/chai/utils/proxify.js +++ b/lib/chai/utils/proxify.js @@ -112,10 +112,12 @@ function stringDistance(strA, strB, memo) { if (strA.length === 0 || strB.length === 0) { memo[strA.length][strB.length] = Math.max(strA.length, strB.length); } else { + var sliceA = strA.slice(0, -1); + var sliceB = strB.slice(0, -1); memo[strA.length][strB.length] = Math.min( - stringDistance(strA.slice(0, -1), strB, memo) + 1, - stringDistance(strA, strB.slice(0, -1), memo) + 1, - stringDistance(strA.slice(0, -1), strB.slice(0, -1), memo) + + stringDistance(sliceA, strB, memo) + 1, + stringDistance(strA, sliceB, memo) + 1, + stringDistance(sliceA, sliceB, memo) + (strA.slice(-1) === strB.slice(-1) ? 0 : 1) ); }