r/cpp_questions • u/MillenniumDev • 7d ago
SOLVED Performance of std::vector
In the university we had to implement quicksort, the unsigned ints are stored in std::vector. I have accidentally discovered, that all algorithms, despite how students implemented them, are much faster when instead of directly accessing data from the vector like that:
arr[n]
we write:
unsigned int *a = arr.data()
and access that data by writing:
a[n]
But I can't understand why is that, in both cases it translates to one and the same: *(a + n)
The code is compiled on Clion IDE if that changes anything, no custom settings for compilation are used.
I can't directly share the algorithms for copyright reasons as they are not mine.
View all comments
2
u/frnxt 7d ago
IME it's pretty common to use vectors exactly like this : most of the C++ code just uses methods/accessors from the STL, and a few very optimized algorithms (as small as possible and wrapped so they're safe to call from the rest of the code) manipulate data() pointers directly.
Even if release builds optimize the C++ methods out, in some cases this can make debug builds slower and therefore more difficult to work with, and sometimes the safety-speed tradeoff would rather go the "speed" direction for legitimate reasons.