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.

34 Upvotes

63 comments sorted by

View all comments

Show parent comment

1

u/No_Engineering_1155 4d ago

Interesting idea, but if I had to implement a quicksort for a vector, I'd rather have a ref as input, otherwise, how would you change the array element order, or maybe much better a span like thingy, or if the students only want a 2 index solution, first-last. And here, I would assume, that the data pointer is pretty hot. Would you think, that this could case some sort of difference?

1

u/AkaMagicEye 3d ago

Yeah sadly I've never found a nice way to do this but having a reference to a struct that contains a pointer to your array will alway be worse and as a vector also includes a length passing it as value has an overhead too. All of that to say: it's not the compilers fault. It cannot optimize that away.