开发者

Array performance question

开发者 https://www.devze.com 2022-12-25 11:01 出处:网络
I am very familiar with STL vector (and other container) performance guarantees, however I can\'t seem to find anything concrete about plain arrays.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号