Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: Binary search in token store utils.search #17066

Merged
merged 3 commits into from Apr 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 21 additions & 16 deletions lib/source-code/token-store/utils.js
Expand Up @@ -4,20 +4,6 @@
*/
"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
* Gets `token.range[0]` from the given token.
* @param {Node|Token|Comment} token The token to get.
* @returns {number} The start location.
* @private
*/
function getStartLocation(token) {
return token.range[0];
}

//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
Expand All @@ -30,9 +16,28 @@ function getStartLocation(token) {
* @returns {number} The found index or `tokens.length`.
*/
exports.search = function search(tokens, location) {
const index = tokens.findIndex(el => location <= getStartLocation(el));
for (let minIndex = 0, maxIndex = tokens.length - 1; minIndex <= maxIndex;) {

return index === -1 ? tokens.length : index;
/*
* Calculate the index in the middle between minIndex and maxIndex.
* `| 0` is used to round a fractional value down to the nearest integer: this is similar to
* using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to
* be faster.
*/
const index = (minIndex + maxIndex) / 2 | 0;
fasttime marked this conversation as resolved.
Show resolved Hide resolved
const token = tokens[index];
const tokenStartLocation = token.range[0];

if (location <= tokenStartLocation) {
if (index === minIndex) {
return index;
}
maxIndex = index;
} else {
minIndex = index + 1;
}
}
return tokens.length;
};

/**
Expand Down