Add an early-out to QVector::operator+= and QHash::unite for empty LHS

If the container being added to is default constructed and has never
been modified, we don't have to do all the checking and iterating.
Instead we can just assign with operator=.

If the LHS is merely empty, we could lose reserve()d capacity, so only
do this for a shared-null LHS.

Change-Id: If1e3342662d10833babc7ab847ada0285073723b
Reviewed-by: Marc Mutz <marc.mutz@kdab.com>
Reviewed-by: Milian Wolff <milian.wolff@kdab.com>
This commit is contained in:
Ulf Hermann 2016-04-25 14:43:43 +02:00
parent b393641888
commit 9366a8be1e
2 changed files with 30 additions and 22 deletions

View File

@ -554,11 +554,15 @@ QHash<Key, T>::createNode(uint ah, const Key &akey, const T &avalue, Node **anex
template <class Key, class T>
Q_INLINE_TEMPLATE QHash<Key, T> &QHash<Key, T>::unite(const QHash &other)
{
QHash copy(other);
const_iterator it = copy.constEnd();
while (it != copy.constBegin()) {
--it;
insertMulti(it.key(), it.value());
if (d == &QHashData::shared_null) {
*this = other;
} else {
QHash copy(other);
const_iterator it = copy.constEnd();
while (it != copy.constBegin()) {
--it;
insertMulti(it.key(), it.value());
}
}
return *this;
}

View File

@ -793,24 +793,28 @@ QVector<T> &QVector<T>::fill(const T &from, int asize)
template <typename T>
QVector<T> &QVector<T>::operator+=(const QVector &l)
{
uint newSize = d->size + l.d->size;
const bool isTooSmall = newSize > d->alloc;
if (!isDetached() || isTooSmall) {
QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
reallocData(d->size, isTooSmall ? newSize : d->alloc, opt);
}
if (d->alloc) {
T *w = d->begin() + newSize;
T *i = l.d->end();
T *b = l.d->begin();
while (i != b) {
if (QTypeInfo<T>::isComplex)
new (--w) T(*--i);
else
*--w = *--i;
if (d == Data::sharedNull()) {
*this = l;
} else {
uint newSize = d->size + l.d->size;
const bool isTooSmall = newSize > d->alloc;
if (!isDetached() || isTooSmall) {
QArrayData::AllocationOptions opt(isTooSmall ? QArrayData::Grow : QArrayData::Default);
reallocData(d->size, isTooSmall ? newSize : d->alloc, opt);
}
if (d->alloc) {
T *w = d->begin() + newSize;
T *i = l.d->end();
T *b = l.d->begin();
while (i != b) {
if (QTypeInfo<T>::isComplex)
new (--w) T(*--i);
else
*--w = *--i;
}
d->size = newSize;
}
d->size = newSize;
}
return *this;
}