본문 바로가기

Windows

[VisualStudio] stl::map insert vs operator[]. Which is faster?

 I was wondering which was faster. So I made a test code and tested.


static int nCDCreated = 0;
static int nCDDestoryed = 0;
static int nCDCopied = 0;
class CD {
public:
    CD() { ++nCDCreated; }
    virtual ~CD() { ++nCDDestoryed; }
    void operator = (const CD& src) {
        i = src.i;
        ++nCDCopied;
    }
    int i;
};

int main(int argc, char* argv[])
{
    std::map<int, std::string> tm;    
    std::map<int, CD> tma;
    

    unsigned long long start;
    const int repeat = 50000;

    nCDCreated = 0;
    nCDDestoryed = 0;
    nCDCopied = 0;
    start = GetTickCount64();
    int i = repeat;
    for (; i > 0; i--) {
        CD testCD;
        testCD.i = i;
        tma.insert(std::pair<int, CD>(i, testCD));
    }
    
    printf("insert : con %d, dest %d copy %d, (%dms)\n", nCDCreated, nCDDestoryed, nCDCopied, GetTickCount64() - start);

    nCDCreated = 0;
    nCDDestoryed = 0;
    nCDCopied = 0;
    tma.clear();
    start = GetTickCount64();
    i = repeat;
    for (; i > 0; i--) {
        CD testCD;
        testCD.i = i;
        tma[i] = testCD;
    }
    printf("operator[] : con %d, dest %d copy %d,  (%dms)\n", nCDCreated, nCDDestoryed, nCDCopied, GetTickCount64() - start);
}


In debug mode, insert function is a little faster than operator[].

insert : con 50000, dest 100000 copy 0, (1125ms)
operator[] : con 100000, dest 100000 copy 50000,  (1406ms)

But in release mode, insert function is almost 14 times faster than operator[].

insert : con 50000, dest 100000 copy 0, (47ms)
operator[] : con 100000, dest 100000 copy 50000,  (672ms)

As the test results, using insert function is better than operator[].




'Windows' 카테고리의 다른 글

Obtaining the title of another application  (0) 2017.01.25
[MFC] Directory Dialog  (0) 2016.08.24
VC6 Static control double click 처리하기  (0) 2016.06.22
[MFC] Double buffering  (0) 2016.05.27
[MFC] Draw Text  (0) 2016.05.27