Skip to content

Commit

Permalink
fix: avoid repeated String#slice calls in stringDistance. (#1095)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bmeurer authored and lucasfcosta committed Dec 2, 2017
1 parent 9a6610e commit eae99d1
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/chai/utils/proxify.js
Expand Up @@ -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)
);
}
Expand Down

0 comments on commit eae99d1

Please sign in to comment.