Is accessing an array is faster than accessing vector? [duplicate]

蓝咒 提交于 2020-01-06 01:54:15

问题


Possible Duplicates:
Using arrays or std::vectors in C++, what's the performance gap?
std::vector is so much slower than plain arrays?

memory is vector of 1000 elements array[] is an integer array of 1000 elements

for (iteration = 0; iteration < numiterations; iteration++) {
    for (j = 1; j < numints; j++) {
       memory[j] += memory[j - 1];
       //array[j] += array[j - 1];
    }
}

If I compare the time of the for loop after running 100 iterations, time required for accessing is very much small compared to that of vector

why is the case ? because I thought both takes constant and nearly same time ..


回答1:


Since most (if not all) implementations of std::vector use a T* array internally, there should be no performance difference at all between accessing a vector element and a C-array element using the [] operator when optimization flags are set. Try your test again using your compiler's optimization flags.

However, this may not be the case using the std::vector<T>::at function, since this function will perform a bounds check.




回答2:


This will typically depend (almost entirely) upon whether you've set the compiler to inline functions. std::vector uses a function (named operator[]) to address items. If that function isn't generated inline, the overhead of calling the function will add a substantial amount to the time taken to address an item in the array. If you set the compiler to generate inline functions, you normally won't be able to measure a meaningful difference between the two.




回答3:


True, they both are constant time. However, a vector is an object and there is a penalty for redirecting function calls. Consider this your first experience with C++ operator overloading. The vector class overloads the [] operator to achieve similar semantics with a real array.



来源:https://stackoverflow.com/questions/3951918/is-accessing-an-array-is-faster-than-accessing-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!