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

后端 未结 22 2379
南方客
南方客 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:13

    Using the following:

    g++ -O3 Time.cpp -I
    ./a.out
    UseArray completed in 2.196 seconds
    UseVector completed in 4.412 seconds
    UseVectorPushBack completed in 8.017 seconds
    The whole thing completed in 14.626 seconds

    So array is twice as quick as vector.

    But after looking at the code in more detail this is expected; as you run across the vector twice and the array only once. Note: when you resize() the vector you are not only allocating the memory but also running through the vector and calling the constructor on each member.

    Re-Arranging the code slightly so that the vector only initializes each object once:

     std::vector  pixels(dimensions * dimensions, Pixel(255,0,0));
    

    Now doing the same timing again:

    g++ -O3 Time.cpp -I
    ./a.out
    UseVector completed in 2.216 seconds

    The vector now performance only slightly worse than the array. IMO this difference is insignificant and could be caused by a whole bunch of things not associated with the test.

    I would also take into account that you are not correctly initializing/Destroying the Pixel object in the UseArrray() method as neither constructor/destructor is not called (this may not be an issue for this simple class but anything slightly more complex (ie with pointers or members with pointers) will cause problems.

提交回复
热议问题