My question is basically when to choose QVector
and when to choose QList
as your Qt container. What I already know:
- Qt docs: QList class
For most purposes, QList is the right class to use. Its index-based API is more convenient than QLinkedList's iterator-based API, and it is usually faster than QVector because of the way it stores its items in memory. It also expands to less code in your executable.
The same is written is this very popular Q&A: QVector vs QList. It also favors QList.
But: on recent Qt World Summit 2015 KDAB presented "Why QList is harmful", this is basically here:
Don't use QList, use Q_DECLARE_TYPEINFO
As far as I understand the idea is that QList
for almost all types is inefficient when allocating new elements in heap. Each time you are adding new element, it calls new
(once per element) and this is inefficient compared to QVector
.
This is why now I am trying to understand: is it QVector
which we should choose as default container?
Imagine, that we have DataType class.
QVector - array of objects, such as:
QList - array of pointers to objects, such as:
Therefore, direct access by index will be faster for QVector:
But swaping will be faster for QList, if sizeof(DataType) > sizeof(DataType*):
So, if you need direct access without swaping operations between elements (such as sorting, for example), or sizeof(DataType) <= sizeof(DataType*), your better way is use QVector. In other case use QList.