QList vs QVector revisited

后端 未结 8 2143
天涯浪人
天涯浪人 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:34

    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.

    I'd tend to say the opposite. It'll be much worse off, when going through the items. If it stores it as pointers on the heap won't QList be much worse off than QVector? The reason that sequential storage(QVector all the time) is so good is, that is is cache friendly, once you store pointers,you lose the data locality, start getting cache misses and it's horrible for performance.

    The "default" container IMHO should be a QVector (or std::vector), if you're worried about lots of reallocation, then preallocate a reasonable amount, pay the once off cost and you'll benefit in the long run.

    Use the *Vector by default, if you get performance problems, profile and change as necessary.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题