From 8010e906d3612aface0daccde41d1a65fca04b0c Mon Sep 17 00:00:00 2001 From: Mat Sutcliffe Date: Tue, 2 Jul 2019 02:16:41 +0100 Subject: Optimize non-const overload of QJsonObject::operator[] Refactored parts of insert() into a new private method insertAt(), which can also be called by operator[]() to avoid a redundant key lookup. This is in preparation for overloading QJsonObject's non-const methods on QLatin1String. As a bonus, this also avoids a redundant key lookup in QJsonValueRef::operator=(). Change-Id: Ic481981d838e50bc55fb8e7844536749781899ce Reviewed-by: Marc Mutz Reviewed-by: Anton Kudryavtsev Reviewed-by: Thiago Macieira --- src/corelib/serialization/qjsonobject.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'src/corelib/serialization/qjsonobject.cpp') diff --git a/src/corelib/serialization/qjsonobject.cpp b/src/corelib/serialization/qjsonobject.cpp index c1a6328b2f..a13dd3f9e7 100644 --- a/src/corelib/serialization/qjsonobject.cpp +++ b/src/corelib/serialization/qjsonobject.cpp @@ -446,11 +446,10 @@ QJsonValue QJsonObject::operator [](const QString &key) const */ QJsonValueRef QJsonObject::operator [](const QString &key) { - // ### somewhat inefficient, as we lookup the key twice if it doesn't yet exist bool keyExists = false; - int index = o ? o->indexOf(key, &keyExists) : -1; + int index = o ? o->indexOf(key, &keyExists) : 0; if (!keyExists) { - iterator i = insert(key, QJsonValue()); + iterator i = insertAt(index, key, QJsonValue(), false); index = i.i; } return QJsonValueRef(this, index); @@ -485,6 +484,16 @@ QJsonObject::iterator QJsonObject::insert(const QString &key, const QJsonValue & remove(key); return end(); } + bool keyExists = false; + int pos = o ? o->indexOf(key, &keyExists) : 0; + return insertAt(pos, key, value, keyExists); +} + +/*! + \internal + */ +QJsonObject::iterator QJsonObject::insertAt(int pos, const QString &key, const QJsonValue &value, bool keyExists) +{ QJsonValue val = value; bool latinOrIntValue; @@ -500,8 +509,6 @@ QJsonObject::iterator QJsonObject::insert(const QString &key, const QJsonValue & if (!o->length) o->tableOffset = sizeof(QJsonPrivate::Object); - bool keyExists = false; - int pos = o->indexOf(key, &keyExists); if (keyExists) ++d->compactionCounter; @@ -1289,7 +1296,7 @@ void QJsonObject::setValueAt(int i, const QJsonValue &val) Q_ASSERT(o && i >= 0 && i < (int)o->length); QJsonPrivate::Entry *e = o->entryAt(i); - insert(e->key(), val); + insertAt(i, e->key(), val, true); } uint qHash(const QJsonObject &object, uint seed) -- cgit v1.2.3