Is std::vector so much slower than plain arrays?

后端 未结 22 2410
南方客
南方客 2020-11-22 12:00

I\'ve always thought it\'s the general wisdom that std::vector is \"implemented as an array,\" blah blah blah. Today I went down and tested it, and it seems to

22条回答
  •  难免孤独
    2020-11-22 12:27

    My laptop is Lenova G770 (4 GB RAM).

    The OS is Windows 7 64-bit (the one with laptop)

    Compiler is MinGW 4.6.1.

    The IDE is Code::Blocks.

    I test the source codes of the first post.

    The results

    O2 optimization

    UseArray completed in 2.841 seconds

    UseVector completed in 2.548 seconds

    UseVectorPushBack completed in 11.95 seconds

    The whole thing completed in 17.342 seconds

    system pause

    O3 optimization

    UseArray completed in 1.452 seconds

    UseVector completed in 2.514 seconds

    UseVectorPushBack completed in 12.967 seconds

    The whole thing completed in 16.937 seconds

    It looks like the performance of vector is worse under O3 optimization.

    If you change the loop to

        pixels[i].r = i;
        pixels[i].g = i;
        pixels[i].b = i;
    

    The speed of array and vector under O2 and O3 are almost the same.

提交回复
热议问题