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

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

    Here's how the push_back method in vector works:

    1. The vector allocates X amount of space when it is initialized.
    2. As stated below it checks if there is room in the current underlying array for the item.
    3. It makes a copy of the item in the push_back call.

    After calling push_back X items:

    1. The vector reallocates kX amount of space into a 2nd array.
    2. It Copies the entries of the first array onto the second.
    3. Discards the first array.
    4. Now uses the second array as storage until it reaches kX entries.

    Repeat. If you're not reserving space its definitely going to be slower. More than that, if it's expensive to copy the item then 'push_back' like that is going to eat you alive.

    As to the vector versus array thing, I'm going to have to agree with the other people. Run in release, turn optimizations on, and put in a few more flags so that the friendly people at Microsoft don't #@%$^ it up for ya.

    One more thing, if you don't need to resize, use Boost.Array.

提交回复
热议问题