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

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

    Assuming a fixed-length array (e.g. int* v = new int[1000]; vs std::vector v(1000);, with the size of v being kept fixed at 1000), the only performance consideration that really matters (or at least mattered to me when I was in a similar dilemma) is the speed of access to an element. I looked up the STL's vector code, and here is what I found:

    const_reference
    operator[](size_type __n) const
    { return *(this->_M_impl._M_start + __n); }
    

    This function will most certainly be inlined by the compiler. So, as long as the only thing that you plan to do with v is access its elements with operator[], it seems like there shouldn't really be any difference in performance.

提交回复
热议问题