From 3a3b76e040ec800e1f3214803c051afacfdb0f7b Mon Sep 17 00:00:00 2001 From: Ahmad Samir Date: Sun, 11 Dec 2022 15:35:34 +0200 Subject: QString: don't detach in insert(qsizetype, QUtf8StringView) If the string is shared, instead of detaching (which would copy the whole string data before doing the insertion), create a new string and copy characters to it as needed then swap it with "this". [ChangeLog][QtCore][QString] Inserting Utf8 data (e.g. a QUtf8StringView) into a currently shared QString is now done more efficiently. Task-number: QTBUG-106186 Change-Id: I832bde1494108685cc2f630750dfe9b38cd96931 Reviewed-by: Thiago Macieira --- src/corelib/text/qstring.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src/corelib/text') diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp index b6c36e1b2f..e0415d65e0 100644 --- a/src/corelib/text/qstring.cpp +++ b/src/corelib/text/qstring.cpp @@ -3031,6 +3031,22 @@ QString &QString::insert(qsizetype i, QUtf8StringView s) if (Q_UNLIKELY(i > d.size)) difference = i - d.size; + const qsizetype newSize = d.size + difference + insert_size; + + if (d.needsDetach() || needsReallocate(*this, newSize)) { + const auto cbegin = this->cbegin(); + const auto insert_start = difference == 0 ? std::next(cbegin, i) : cend(); + QString other; + other.reserve(newSize); + other.append(QStringView(cbegin, insert_start)); + if (difference > 0) + other.resize(i, u' '); + other.append(s); + other.append(QStringView(insert_start, cend())); + swap(other); + return *this; + } + if (i >= d.size) { d.detachAndGrow(QArrayData::GrowsAtEnd, difference + insert_size, nullptr, nullptr); Q_CHECK_PTR(d.data()); -- cgit v1.2.3