1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 23:27:43 +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

@ -777,10 +777,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::repeat)
return PrimitiveString::create(vm, String {});
// 6. Return the String value that is made from n copies of S appended together.
StringBuilder builder;
for (size_t i = 0; i < n; ++i)
builder.append(string);
return PrimitiveString::create(vm, MUST(builder.to_string()));
return PrimitiveString::create(vm, String::repeated(string, n));
}
// 22.1.3.19 String.prototype.replace ( searchValue, replaceValue ), https://tc39.es/ecma262/#sec-string.prototype.replace