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

后端 未结 19 1665
忘了有多久
忘了有多久 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:22

    You have even fewer reasons to use plain arrays in C++11.

    There are 3 kind of arrays in nature from fastest to slowest, depending on the features they have (of course the quality of implementation can make things really fast even for case 3 in the list):

    1. Static with size known at compile time. --- std::array
    2. Dynamic with size known at runtime and never resized. The typical optimization here is, that if the array can be allocated in the stack directly. -- Not available. Maybe dynarray in C++ TS after C++14. In C there are VLAs
    3. Dynamic and resizable at runtime. --- std::vector

    For 1. plain static arrays with fixed number of elements, use std::array in C++11.

    For 2. fixed size arrays specified at runtime, but that won't change their size, there is discussion in C++14 but it has been moved to a technical specification and made out of C++14 finally.

    For 3. std::vector will usually ask for memory in the heap. This could have performance consequences, though you could use std::vector> to improve the situation with a custom allocator. The advantage compared to T mytype[] = new MyType[n]; is that you can resize it and that it will not decay to a pointer, as plain arrays do.

    Use the standard library types mentioned to avoid arrays decaying to pointers. You will save debugging time and the performance is exactly the same as with plain arrays if you use the same set of features.

提交回复
热议问题