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

Replace keyword Regexps with Sets for improved performance #1342

Open
dmichon-msft opened this issue Jan 23, 2025 · 0 comments
Open

Replace keyword Regexps with Sets for improved performance #1342

dmichon-msft opened this issue Jan 23, 2025 · 0 comments

Comments

@dmichon-msft
Copy link

On modern runtimes, testing identifiers for matches with keywords is significantly (up to 60%) faster by using Set than by using a RegExp.

The lookup is faster still if you first check the length of the identifier to avoid computing hashcodes for strings that are too long or too short to match.

Sample code:

function createTester(words) {
  let minLength = Infinity;
  let maxLength = 0;
  const split = words.split(' ');
  const set = new Set();
  for (let i = 0; i < split.length; i++) {
    const word = split[i];
    set.add(word);
    if (word.length < minLength) minLength = word.length;
    if (word.length > maxLength) maxLength = word.length;
  }

  return regexpCache[words] = {
    test: function (input) {
      // Length testing the string is cheaper than computing the hash code for long strings
      return input.length >= minLength && input.length <= maxLength && set.has(input)
    }
  }
}

export function wordsRegexp(words) {
  return regexpCache[words] || createTester(words)
}

Existing implementation:
Image

Impact of suggested implementation:
Image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant