What's the fastest QVector operation
Hello!
In copying some large data (lets say from an array) to a QVector, what should be faster?
Option 1:
Code:
for (int aaa = 0; aaa < SIZE_TO_COPY; aaa++)
{
myVector.append(myArray[aaa]);
}
Option 2:
Code:
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
Re: What's the fastest QVector operation
Option 2 is faster than option 1.
Re: What's the fastest QVector operation
You should probably also benchmark using an explicit memcpy from the source array to the target array.
Cheers,
_
Re: What's the fastest QVector operation
Provided that the data type stored can be copied using memcpy.
Re: What's the fastest QVector operation
Quote:
Originally Posted by
wysota
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.
Re: What's the fastest QVector operation
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.
Code:
memcpy(myVector.data(), myArray, length_of_array);