mirror of
https://github.com/fergalmoran/ladybird.git
synced 2026-01-04 15:45:25 +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:
@@ -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 };
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user