QList vs QVector revisited

后端 未结 8 2158
天涯浪人
天涯浪人 2020-12-23 22:00

My question is basically when to choose QVector and when to choose QList as your Qt container. What I already know:

  1. Qt docs: QList cl
8条回答
  •  误落风尘
    2020-12-23 22:39

    QList is the best possible container to use generally as the documentation states. If the size of the elements' type is <= of the pointer's size = machine & OS bitness = 4 or 8 bytes then the objects are stored the same way as QVector does - sequentially in memory. If the size of the QList's element type is greater than the pointer's size QList performs better than QVector because it doesn't store the objects sequentially but stores sequentially pointers to heap copies. In the 32-bit case the picture is as follows:

    sizeof( T ) <= sizeof( void* )
    =====
    QList< T > = [1][1][1][1][1]
                       or
                 [2][2][2][2][2]
                       or
                 [3][3][3][3][3]
                       or
                 [4][4][4][4][4] = new T[];
    
    sizeof( T ) > sizeof( void* )
    =====
    QList< T > = [4][4][4][4][4] = new T*[]; // 4 = pointer's size
                  |   |  ...  |
               new T new T   new T
    

    In case you want your objects to be laid out sequentially in memory no matter the size of their elements, as it is usually the case with OpenGL programming, then you should use QVector.

    Here is a detailed description of the QList's internals.

提交回复
热议问题