Vector vs. Arrays: A Performance Quandary
In C , the use of arrays has been discouraged in favor of std::vectors. However, the extent of performance differences has often been questioned.
Avoidance of C Arrays
Current guidelines suggest avoiding new-allocated C arrays, as they require manual tracking and deletion. Additionally, using arrays on the stack is discouraged due to the lack of range checking and size information loss during pointer conversion. In such cases, std::array is recommended, providing size functions and iterators.
std::Vector vs. Native Arrays
Empirical findings reveal that basic indexing, dereferencing, and increment operations on vectors perform identically to their corresponding array/pointer counterparts. Assembly code analysis confirms this equivalence (see code snippet below).
int pointer_index(S &s) { return s.p[3]; } // Analogous to vector indexing int vector_index(S &s) { return s.v[3]; } // Same assembly code
int pointer_deref(S &s) { return *s.p; } // Analogous to iterator dereferencing int iterator_deref(S &s) { return *s.i; } // Identical assembly code
void pointer_increment(S &s) { ++s.p; } // Analogous to iterator increment void iterator_increment(S &s) { ++s.i; } // Same assembly code
Exception: Performance Advantage of New-Allocated Arrays
One exception to the performance equivalence is for new-allocated arrays containing non-class objects or classes without user-defined constructors. In this case, new-allocated arrays can provide an advantage over std::vectors, as std::vectors initialize elements to default values (e.g., 0 for int) on construction.
The above is the detailed content of When Does `std::vector` Outperform Raw Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!