From c12f42e91b146109cc9ee5d050928672776ca1ee Mon Sep 17 00:00:00 2001 From: Anton Kudryavtsev Date: Wed, 26 Oct 2016 20:53:23 +0300 Subject: QString: optimize replace(QChar, QChar, Qt::CaseSensitivity) Only detach() if the string does contain the character to be replaced. Save memory allocations. Change-Id: I69c070d3f0b99f505fb6c209f657cdce31a35461 Reviewed-by: Edward Welbourne --- src/corelib/tools/qstring.cpp | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index 8db865cfa6..27d8c14583 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -2633,21 +2633,28 @@ QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs */ QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs) { - ushort a = after.unicode(); - ushort b = before.unicode(); if (d->size) { - detach(); - ushort *i = d->data(); - const ushort *e = i + d->size; - if (cs == Qt::CaseSensitive) { - for (; i != e; ++i) - if (*i == b) - *i = a; - } else { - b = foldCase(b); - for (; i != e; ++i) - if (foldCase(*i) == b) - *i = a; + const int idx = indexOf(before, 0, cs); + if (idx != -1) { + detach(); + const ushort a = after.unicode(); + ushort *i = d->data(); + const ushort *e = i + d->size; + i += idx; + *i = a; + if (cs == Qt::CaseSensitive) { + const ushort b = before.unicode(); + while (++i != e) { + if (*i == b) + *i = a; + } + } else { + const ushort b = foldCase(before.unicode()); + while (++i != e) { + if (foldCase(*i) == b) + *i = a; + } + } } } return *this; -- cgit v1.2.3