summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRĂ©mi Verschelde <remi@verschelde.fr>2022-08-23 08:52:50 +0200
committerGitHub <noreply@github.com>2022-08-23 08:52:50 +0200
commitb368985291f97fa79d2130a241026141076ac202 (patch)
tree0709170fb10361e5e080b2c7133fa4bae68270d9
parent62c3e72b6f3e6fb628ffcb2d062dcbb5de304867 (diff)
parentdae64e5361aa2be19ad663d443f0c8050f0493f0 (diff)
Merge pull request #64489 from MewPurPur/fast-string-repeat
Improved performance of `String.repeat()`
-rw-r--r--core/string/ustring.cpp25
1 files changed, 13 insertions, 12 deletions
diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp
index 13be7516d5..c02be9e5b7 100644
--- a/core/string/ustring.cpp
+++ b/core/string/ustring.cpp
@@ -3451,18 +3451,19 @@ String String::replacen(const String &p_key, const String &p_with) const {
String String::repeat(int p_count) const {
ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
- String new_string;
- const char32_t *src = this->get_data();
-
- new_string.resize(length() * p_count + 1);
- new_string[length() * p_count] = 0;
-
- for (int i = 0; i < p_count; i++) {
- for (int j = 0; j < length(); j++) {
- new_string[i * length() + j] = src[j];
- }
- }
-
+ int len = length();
+ String new_string = *this;
+ new_string.resize(p_count * len + 1);
+
+ char32_t *dst = new_string.ptrw();
+ int offset = 1;
+ int stride = 1;
+ while (offset < p_count) {
+ memcpy(dst + offset * len, dst, stride * len * sizeof(char32_t));
+ offset += stride;
+ stride = MIN(stride * 2, p_count - offset);
+ }
+ dst[p_count * len] = _null;
return new_string;
}