Skip to content

Commit 9d1b8fc

Browse files
authored
perf: Binary search in token store utils.search (#17066)
* perf: Binary search in token store `utils.search` * Use `Math.trunc` * Switch back to `| 0`, inline `getStartLocation`
1 parent 07a4435 commit 9d1b8fc

1 file changed

Lines changed: 21 additions & 16 deletions

File tree

lib/source-code/token-store/utils.js

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,6 @@
44
*/
55
"use strict";
66

7-
//------------------------------------------------------------------------------
8-
// Helpers
9-
//------------------------------------------------------------------------------
10-
11-
/**
12-
* Gets `token.range[0]` from the given token.
13-
* @param {Node|Token|Comment} token The token to get.
14-
* @returns {number} The start location.
15-
* @private
16-
*/
17-
function getStartLocation(token) {
18-
return token.range[0];
19-
}
20-
217
//------------------------------------------------------------------------------
228
// Exports
239
//------------------------------------------------------------------------------
@@ -30,9 +16,28 @@ function getStartLocation(token) {
3016
* @returns {number} The found index or `tokens.length`.
3117
*/
3218
exports.search = function search(tokens, location) {
33-
const index = tokens.findIndex(el => location <= getStartLocation(el));
19+
for (let minIndex = 0, maxIndex = tokens.length - 1; minIndex <= maxIndex;) {
3420

35-
return index === -1 ? tokens.length : index;
21+
/*
22+
* Calculate the index in the middle between minIndex and maxIndex.
23+
* `| 0` is used to round a fractional value down to the nearest integer: this is similar to
24+
* using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to
25+
* be faster.
26+
*/
27+
const index = (minIndex + maxIndex) / 2 | 0;
28+
const token = tokens[index];
29+
const tokenStartLocation = token.range[0];
30+
31+
if (location <= tokenStartLocation) {
32+
if (index === minIndex) {
33+
return index;
34+
}
35+
maxIndex = index;
36+
} else {
37+
minIndex = index + 1;
38+
}
39+
}
40+
return tokens.length;
3641
};
3742

3843
/**

0 commit comments

Comments
 (0)