Iterating over a QMap with for

前端 未结 9 1710
执笔经年
执笔经年 2021-01-31 07:02

I\'ve a QMap object and I am trying to write its content to a file.

QMap extensions;
//.. 

for(auto e : extensions)
{
  fou         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 07:45

    For people interested in optimizations, I have tried several approaches, did some micro benchmarks, and I can conclude that STL style approach is significantly faster.

    I have tried adding integers with these methods :

    • QMap::values()
    • Java style iterator (as advised in the documentation)
    • STL style iterator (as advised in the documentation too)

    And I have compared it with summing integers of a QList/QVector

    Results :

    Reference vector :   244  ms
    Reference list :     1239  ms
    
    QMap::values() :     6504  ms
    Java style iterator :    6199  ms
    STL style iterator :     2343  ms
    

    Code for those interested :

    #include 
    #include 
    #include 
    #include 
    #include 
    
    void testQMap(){
        QMap map;
        QVector vec;
        QList list;
    
        int nbIterations = 100;
        int size = 1000000;
        volatile int sum = 0;
    
        for(int i = 0; i values = map.values();
            for(int k : values){
                sum += k;
            }
        }
        qint64 end0 = QDateTime::currentMSecsSinceEpoch();
        qDebug() << "QMap::values() : \t" << (end0-start0) << " ms";
    
    
        // Java style iterator
        qint64 start1 = QDateTime::currentMSecsSinceEpoch();
        for(int i = 0; i it(map);
            while (it.hasNext()) {
                it.next();
                sum += it.value();
            }
        }
        qint64 end1 = QDateTime::currentMSecsSinceEpoch();
        qDebug() << "Java style iterator : \t" << (end1-start1) << " ms";
    
    
        // STL style iterator
        qint64 start2 = QDateTime::currentMSecsSinceEpoch();
        for(int i = 0; i::const_iterator it = map.constBegin();
            auto end = map.constEnd();
            while (it != end) {
                sum += it.value();
                ++it;
            }
        }
        qint64 end2 = QDateTime::currentMSecsSinceEpoch();
        qDebug() << "STL style iterator : \t" << (end2-start2) << " ms";
    
    
        qint64 start3 = QDateTime::currentMSecsSinceEpoch();
        for(int i = 0; i

    Edit July 2017 : I ran this code again on my new laptop (Qt 5.9, i7-7560U) and got some interesting changes

    Reference vector :   155  ms 
    Reference list :     157  ms
    QMap::values():      1874  ms 
    Java style iterator: 1156  ms 
    STL style iterator:  1143  ms
    

    STL style and Java style have very similar performances in this benchmark

提交回复
热议问题