Using arrays or std::vectors in C++, what's the performance gap?

后端 未结 19 1668
忘了有多久
忘了有多久 2020-11-22 03:23

In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know Stroustroup himself suggests not to use arrays. But are there significant perf

19条回答
  •  无人共我
    2020-11-22 04:14

    There is definitely a performance impact to using an std::vector vs a raw array when you want an uninitialized buffer (e.g. to use as destination for memcpy()). An std::vector will initialize all its elements using the default constructor. A raw array will not.

    The c++ spec for the std:vector constructor taking a count argument (it's the third form) states:

    `Constructs a new container from a variety of data sources, optionally using a user supplied allocator alloc.

    1. Constructs the container with count default-inserted instances of T. No copies are made.

    Complexity

    2-3) Linear in count

    A raw array does not incur this initialization cost.

    Note that with a custom allocator, it is possible to avoid "initialization" of the vector's elements (i.e. to use default initialization instead of value initialization). See these questions for more details:

    • Is this behavior of vector::resize(size_type n) under C++11 and Boost.Container correct?
    • How can I avoid std::vector<> to initialize all its elements?

提交回复
热议问题