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

后端 未结 19 1446
忘了有多久
忘了有多久 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 03:58

    Vectors are arrays under the hood. The performance is the same.

    One place where you can run into a performance issue, is not sizing the vector correctly to begin with.

    As a vector fills, it will resize itself, and that can imply, a new array allocation, followed by n copy constructors, followed by about n destructor calls, followed by an array delete.

    If your construct/destruct is expensive, you are much better off making the vector the correct size to begin with.

    There is a simple way to demonstrate this. Create a simple class that shows when it is constructed/destroyed/copied/assigned. Create a vector of these things, and start pushing them on the back end of the vector. When the vector fills, there will be a cascade of activity as the vector resizes. Then try it again with the vector sized to the expected number of elements. You will see the difference.

提交回复
热议问题