diff --git a/crates/oxc_parser/src/lexer/mod.rs b/crates/oxc_parser/src/lexer/mod.rs index ec6d50fea..3cb8f585e 100644 --- a/crates/oxc_parser/src/lexer/mod.rs +++ b/crates/oxc_parser/src/lexer/mod.rs @@ -252,7 +252,14 @@ impl<'a> Lexer<'a> { #[inline] #[allow(clippy::cast_possible_truncation)] fn offset(&self) -> u32 { - (self.source.len() - self.current.chars.as_str().len()) as u32 + // Offset = current position of `chars` relative to start of `source`. + // Previously was `self.source.len() - self.current.chars.as_str().len()`, + // but that was slower because `std::str::Chars` internally is a current pointer + end pointer, + // whereas `&str` internally is a start pointer and len. + // So comparing `len()` of the two requires an extra memory read, and addition operation. + // https://godbolt.org/z/v46MWddTM + // This function is on hot path, so saving even a single instruction makes a measurable difference. + (self.current.chars.as_str().as_ptr() as usize - self.source.as_ptr() as usize) as u32 } /// Get the current unterminated token range