From 381910a51d415007007fee9a723b83c4547ce6e7 Mon Sep 17 00:00:00 2001 From: Tim Ledbetter Date: Mon, 11 May 2026 09:34:42 +0100 Subject: [PATCH] AK: Use `memchr` for `Utf8View::contains()` ASCII fast path The libc implementation of `memchr` uses SIMD, so is significantly faster than looping over individual bytes. --- AK/Utf8View.cpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/AK/Utf8View.cpp b/AK/Utf8View.cpp index bfd7fd95e3..791f1e2c95 100644 --- a/AK/Utf8View.cpp +++ b/AK/Utf8View.cpp @@ -126,18 +126,15 @@ bool Utf8View::starts_with(Utf8View const& start) const bool Utf8View::contains(u32 needle) const { if (needle <= 0x7f) { - // OPTIMIZATION: Fast path for ASCII - for (u8 code_point : as_string()) { - if (code_point == needle) - return true; - } - } else { - for (u32 code_point : *this) { - if (code_point == needle) - return true; - } + // OPTIMIZATION: An ASCII byte can only appear as itself in valid UTF-8, so memchr is safe here. + auto bytes = as_string(); + return memchr(bytes.characters_without_null_termination(), needle, bytes.length()) != nullptr; } + for (u32 code_point : *this) { + if (code_point == needle) + return true; + } return false; }