1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 08:14:58 +00:00

LibJS+AK: Make String.prototype.repeat() way faster

Instead of using a StringBuilder, add a String::repeated(String, N)
overload that takes advantage of knowing it's already all UTF-8.

This makes the following microbenchmark go 4x faster:

    "foo".repeat(100_000_000)

And for single character strings, we can even go 10x faster:

    "x".repeat(100_000_000)
This commit is contained in:
Andreas Kling 2023-12-29 13:20:11 +01:00
parent 9ce267944c
commit a285e36041
3 changed files with 21 additions and 4 deletions

View file

@ -636,4 +636,21 @@ bool String::equals_ignoring_ascii_case(StringView other) const
return StringUtils::equals_ignoring_ascii_case(bytes_as_string_view(), other);
}
String String::repeated(String const& input, size_t count)
{
VERIFY(!Checked<size_t>::multiplication_would_overflow(count, input.bytes().size()));
u8* buffer = nullptr;
auto data = MUST(Detail::StringData::create_uninitialized(count * input.bytes().size(), buffer));
if (input.bytes().size() == 1) {
memset(buffer, input.bytes().first(), count);
return String { move(data) };
}
for (size_t i = 0; i < count; ++i) {
memcpy(buffer + (i * input.bytes().size()), input.bytes().data(), input.bytes().size());
}
return String { data };
}
}