Skip to content

Commit 4ee80ac

Browse files
committed
perf(linter/plugins): remove bounds checks on regex tokens (#20478)
Possibly the most absurd optimization I've ever encountered. ```diff - if (regexObjects.length > regexIndex) { + if (regexIndex < regexObjects.length) { regex = regexObjects[regexIndex]; } ``` There is no semantic difference whatsoever between `regexObjects.length > regexIndex` and `regexIndex < regexObjects.length`. But V8's 2nd-tier Maglev compiler treats them differently. In the`>` version, `regexObjects[regexIndex]` incurs a bounds check, whereas in the new `<` version, no bounds check. This is a micro-optimization, but this function is extremely hot, so it may actually move the needle in code that includes a lot of regexes. The same optimization is also applied in #20480. Claude found this oddity by reading V8's source code!
1 parent c3d9e91 commit 4ee80ac

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

apps/oxlint/src-js/plugins/tokens.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,10 +395,13 @@ function deserializeTokenIfNeeded(index: number): Token | null {
395395
}
396396
} else if (kind === REGEXP_KIND) {
397397
// Reuse cached regex descriptor object if available, otherwise create a new one.
398-
// The array access is inside the `regexObjects.length > regexIndex` branch so V8 can elide the bounds check.
398+
//
399+
// The array access is inside the `regexIndex < regexObjects.length` branch so V8 can remove the bounds check
400+
// on `regexObjects[regexIndex]`. Comparison *must* be this way around. Maglev would *not* remove bounds check
401+
// if comparison was `regexObjects.length > regexIndex`, even though it's semantically equivalent.
399402
let regex: Regex;
400403
const regexIndex = tokensWithRegex.length;
401-
if (regexObjects.length > regexIndex) {
404+
if (regexIndex < regexObjects.length) {
402405
regex = regexObjects[regexIndex];
403406
} else {
404407
regexObjects.push((regex = { pattern: null!, flags: null! }));

0 commit comments

Comments
 (0)