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

32 Upvotes

63 comments sorted by

View all comments

Show parent comment

5

u/Alzurana 6d ago

Just attatching to this answer because you say standard types are built to be optimized very well.

That is 100% true, I just want to attach a very good series on compiler design that also helps understanding how those optimizations take place and how you can potentially have your own code be optimized similarly well by thinking about it's structure just a little bit more:

https://www.youtube.com/watch?v=zA5iLLP9v-I&list=PL6whQ6CW68oe3tcmFcBLYFQChqwYEaG7_

It's also a good resource to realize where you can absolutely be more verbose for readability sake without losing on any performance. (For example, writing a new variable for each new value you calculate). It just all optimizes out. Or even avoiding ternary operators if an "if" block is more readable.

Similarly, the compiler will reorder instructions to promote hot paths so you do not have to do that yourself, you can think about readability first. There's ways to give hints to likely branches with the "likely" keyword, as well.