问题
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