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.
This commit is contained in:
Tim Ledbetter 2026-05-11 09:34:42 +01:00 committed by Jelle Raaijmakers
parent 2fda5ffc9b
commit 381910a51d

View file

@ -126,18 +126,15 @@ bool Utf8View::starts_with(Utf8View const& start) const
bool Utf8View::contains(u32 needle) const bool Utf8View::contains(u32 needle) const
{ {
if (needle <= 0x7f) { if (needle <= 0x7f) {
// OPTIMIZATION: Fast path for ASCII // OPTIMIZATION: An ASCII byte can only appear as itself in valid UTF-8, so memchr is safe here.
for (u8 code_point : as_string()) { auto bytes = as_string();
if (code_point == needle) return memchr(bytes.characters_without_null_termination(), needle, bytes.length()) != nullptr;
return true;
}
} else {
for (u32 code_point : *this) {
if (code_point == needle)
return true;
}
} }
for (u32 code_point : *this) {
if (code_point == needle)
return true;
}
return false; return false;
} }