PDA

View Full Version : What's the fastest QVector operation



Momergil
29th May 2014, 13:36
Hello!

In copying some large data (lets say from an array) to a QVector, what should be faster?

Option 1:


for (int aaa = 0; aaa < SIZE_TO_COPY; aaa++)
{
myVector.append(myArray[aaa]);
}


Option 2:


const int startPoint = myVector.size();
const int lastPos = startPoint + SIZE_TO_COPY;
myVector.resize(lastPos); //(myVector.size() + SIZE_TO_COPY)

for (int aaa = startPoint, bbb = 0; aaa < lastPos; aaa++, bbb++)
{
myVector.replace(aaa,myArray[bbb]);
}


Modifier 1: Include myVector.reserve(myVector.size() + SIZE_TO_COPY); before the loop in the first option or before the resize() in the second option.
Modifier 2: Use foreach(...) instead of for(...).

Thanks,

Momergil

wysota
29th May 2014, 15:53
Option 2 is faster than option 1.

anda_skoa
29th May 2014, 18:56
You should probably also benchmark using an explicit memcpy from the source array to the target array.

Cheers,
_

wysota
29th May 2014, 21:07
Provided that the data type stored can be copied using memcpy.

Momergil
30th May 2014, 14:00
Provided that the data type stored can be copied using memcpy.

Yeah, for my particular situation that inspired me to do this question, I'ld say memcpy is not allowed (the vector is a vector of double, and the array is an array of short). But in any case, how could I do a memcpy from an array to a QVector if their types were compatible? memcpy(&myVector,myArray,sizeof(myArray)) doesn't seem that would work.

wysota
30th May 2014, 16:22
You can safely copy doubles from one vector to another using memcpy. You cannot copy classes that have non-trivial constructors. memcpy() accepts addresses where it should copy to/from.


memcpy(myVector.data(), myArray, length_of_array);