r/cpp_questions • • 15d 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.

32 Upvotes

63 comments sorted by

View all comments

1

u/Raknarg 15d ago edited 15d ago

Can you share the compiler settings and the compiler being used? We can use godbolt and take a look at the assembly to see whats going on. My guess though is just that you haven't enabled optimizations and one of these forms has some default optimizations that are better. If you enable -O3 or whatever the max optimization is for your compiler I would be surprised if there was a difference.

I tested it myself in godbolt but the assembly doesn't give any hint why one would be slower, they both invoke a function call with similar operations in gcc trunk and clang. So I'd need whatever compiler you're using.

edit: Another thing I thought of, are you only calling data() once and reusing that result? Because that would mean in a loop with 100 elements the data() version would be calling the function just once, while the operator[] version would be calling a function every time.