Array performance question
I am very familiar with STL vector (and other container) performance guarantees, however I can't seem to find anything concrete about plain arrays.
Are pointer arithmetic and [] methods constant or linea开发者_开发知识库r time?
They are constant time. (Same as vector
.)
When you say a[b]
, it becomes *(a + b)
. Both (pointer arithmetic) addition and dereferencing are constant time.
When adding an integer to a pointer, it moves that many elements over:
T* p; size_t i;
T* q = p + i; // same as:
T* q = reinterpret_cast<T*>(reinterpret_cast<char*>(p) + i * sizeof(T));
Every operation in there is constant time.
A vector is effectively a wrapper around an array, so they should both provide the same performance guarantees.
Pointer arithmetic is constant - it's usually a single multiplication and addition to base. [] is a kind of pointer arithmetic as well.
精彩评论