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

34 Upvotes

63 comments sorted by

View all comments

35

u/QuentinUK 7d ago

arr[n] for a vector calls a subroutine int std::vector<int>::operator[](size_t index); which can be optimised away to *(a+n) but in Debug mode that isn’t done so will be slower. In debug mode there are also checks that the index does not go out of bounds for the array which slow things down.

2

u/KingAggressive1498 6d ago

yep. way way back before I got pretty good at debugging optimized builds I used to do hacks like this instead of using the std algorithms all the time because "iterators are slow".

1

u/bkubicek 5d ago

A while ago this was not true. Range checking was only possible using .at()

-4

u/Raknarg 7d ago

but data() is also a subroutine, so both versions should be invoking a subroutine call.

16

u/WhiteEvilBro 7d ago

.data() needs to be invoked once, while operator[] is invoked on every read and write (therefore O(nlogn) times)