From 5c46d07a7ce1542301b6e428f9f8d07738e7518f Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Tue, 12 Jul 2016 12:37:16 +0200 Subject: [PATCH] Optimize QString::insert() When the insertion position is not beyond end(), call resize() instead of expand(), which fills the new size with spaces, which, however would just be overwritten by the following memmove(). Add some Q_UNLIKELY to indicate that we strongly expect the resize() case to be the more common. Change-Id: Iaf3215dd53c2cbd18f2fd8a5f80af8f6844944da Reviewed-by: Edward Welbourne Reviewed-by: Anton Kudryavtsev Reviewed-by: Thiago Macieira --- src/corelib/tools/qstring.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index 629a0bc744c..9dc7136d2a1 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -1985,7 +1985,10 @@ QString &QString::insert(int i, QLatin1String str) return *this; int len = str.size(); - expand(qMax(d->size, i) + len - 1); + if (Q_UNLIKELY(i > d->size)) + expand(i + len - 1); + else + resize(d->size + len); ::memmove(d->data() + i + len, d->data() + i, (d->size - i - len) * sizeof(QChar)); qt_from_latin1(d->data() + i, s, uint(len)); @@ -2015,7 +2018,10 @@ QString& QString::insert(int i, const QChar *unicode, int size) return *this; } - expand(qMax(d->size, i) + size - 1); + if (Q_UNLIKELY(i > d->size)) + expand(i + size - 1); + else + resize(d->size + size); ::memmove(d->data() + i + size, d->data() + i, (d->size - i - size) * sizeof(QChar)); memcpy(d->data() + i, s, size * sizeof(QChar)); @@ -2035,7 +2041,10 @@ QString& QString::insert(int i, QChar ch) i += d->size; if (i < 0) return *this; - expand(qMax(i, d->size)); + if (Q_UNLIKELY(i > d->size)) + expand(i); + else + resize(d->size + 1); ::memmove(d->data() + i + 1, d->data() + i, (d->size - i - 1) * sizeof(QChar)); d->data()[i] = ch.unicode(); return *this;