From 3b31ff90084f03c58a41366ed8a2560c9c9cfef3 Mon Sep 17 00:00:00 2001 From: Hugo Locurcio Date: Tue, 23 Aug 2022 14:23:47 +0200 Subject: [PATCH] Optimize `String.repeat()` This backports the optimization done in `master`. Co-authored-by: VolTer --- core/ustring.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/core/ustring.cpp b/core/ustring.cpp index 0c528e88942..2aef60613a4 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -3081,17 +3081,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 CharType *src = this->c_str(); + int len = length(); + String new_string = *this; + new_string.resize(p_count * len + 1); - 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]; - } + CharType *dst = new_string.ptrw(); + int offset = 1; + int stride = 1; + while (offset < p_count) { + memcpy(dst + offset * len, dst, stride * len * sizeof(CharType)); + offset += stride; + stride = MIN(stride * 2, p_count - offset); } + dst[p_count * len] = _null; return new_string; }