From 56ae615b6e089d6269dc17bcef647efd93cf20d0 Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Wed, 31 Jul 2024 03:33:02 +0000 Subject: [PATCH] perf(parser): make not at EOF the hot path in `Source` methods (#4576) Reverse `if` arms in 2 very commonly-called methods in `Source` so that "not at EOF" is the first branch. This will encourage compiler to treat EOF as the cold branch (which it should be, as we're almost never at EOF). --- crates/oxc_parser/src/lexer/source.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/oxc_parser/src/lexer/source.rs b/crates/oxc_parser/src/lexer/source.rs index 4a5b6a256..790be9ab4 100644 --- a/crates/oxc_parser/src/lexer/source.rs +++ b/crates/oxc_parser/src/lexer/source.rs @@ -438,11 +438,12 @@ impl<'a> Source<'a> { #[allow(dead_code)] #[inline] unsafe fn next_byte(&mut self) -> Option { - if self.is_eof() { - None - } else { + #[allow(clippy::if_not_else)] // Hot path first + if !self.is_eof() { // SAFETY: Safe to read from `ptr` as we just checked it's not out of bounds Some(self.next_byte_unchecked()) + } else { + None } } @@ -503,11 +504,12 @@ impl<'a> Source<'a> { /// Peek next byte of source without consuming it. #[inline] pub(super) fn peek_byte(&self) -> Option { - if self.is_eof() { - None - } else { + #[allow(clippy::if_not_else)] // Hot path first + if !self.is_eof() { // SAFETY: Safe to read from `ptr` as we just checked it's not out of bounds Some(unsafe { self.peek_byte_unchecked() }) + } else { + None } }