STL map insertion efficiency: [] vs. insert

前端 未结 6 1703
走了就别回头了
走了就别回头了 2021-02-12 22:23

There are two ways of map insertion:

m[key] = val;

Or

m.insert(make_pair(key, val));

My question is, which op

6条回答
  •  故里飘歌
    2021-02-12 22:54

    On a lightly loaded system with plenty of memory, this code:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    typedef map  MapType;
    const unsigned int NINSERTS = 1000000;
    
    int main() {
        MapType m1;
        string s = "foobar";
        clock_t t = clock();
        for ( unsigned int i = 0; i < NINSERTS; i++ ) {
            m1[i] = s;
        }
        cout << clock() - t << endl;
        MapType m2;
        t = clock();
        for ( unsigned int i = 0; i < NINSERTS; i++ ) {
            m2.insert( make_pair( i, s ) );
        }
        cout << clock() - t << endl;
    }
    

    produces:

    1547
    1453
    

    or similar values on repeated runs. So insert is (in this case) marginally faster.

提交回复
热议问题