From b6e28ff80779520ccb49e6c15ae1866bbc8713a7 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 25 Oct 2024 13:38:55 +0200 Subject: [PATCH] AK: Add ASCII fast path in StringBuilder::append(Utf16View) And let's at least try to pre-allocate an appropriate amount of buffer space in the builder instead of appending and growing one code point at a time. --- AK/StringBuilder.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/AK/StringBuilder.cpp b/AK/StringBuilder.cpp index 28c399c7d30..e259269964b 100644 --- a/AK/StringBuilder.cpp +++ b/AK/StringBuilder.cpp @@ -224,7 +224,19 @@ void StringBuilder::append_code_point(u32 code_point) ErrorOr StringBuilder::try_append(Utf16View const& utf16_view) { + // NOTE: This may under-allocate in the presence of surrogate pairs. + // That's okay, appending will still grow the buffer as needed. + TRY(will_append(utf16_view.length_in_code_units())); + for (size_t i = 0; i < utf16_view.length_in_code_units();) { + // OPTIMIZATION: Fast path for ASCII characters. + auto code_unit = utf16_view.data()[i]; + if (code_unit <= 0x7f) { + append(static_cast(code_unit)); + ++i; + continue; + } + auto code_point = utf16_view.code_point_at(i); TRY(try_append_code_point(code_point));