r/cpp_questions • u/MillenniumDev • 6d 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
1
u/AndriesG04 6d ago
Like the other dude said, compile with optimisations turned on. I also discovered this in my Performance Engineering class and was like, why would anyone use this it’s like 3 times as slow (for mat-mat multiply). But std::vector has been built in such a way that compilers can heavily optimise your code when you use it. I also think, but don’t quote me on this, that compilers also optimise certain stuff when they recognise you use std::vector