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

Show parent comment

2

u/frnxt 7d ago

Signal processing, often with vectors of simple types such as std::vector<float>.

To be honest this is not something I would recommend unconditionally (notably because if I can afford a proper "safe" design, a specialized data structure with control over its allocations is often a better choice), but it's a pattern I found used by multiple people over around 10 years I've been programming C++ so it looks pervasive enough.

2

u/frnxt 7d ago

(Also : we often deal with other external C/C++ libraries for performance, which take pointers, and std::vectors are a very quick way to initialize a pointer to an array containing all the data we might need!)

4

u/ItWasMyWifesIdea 7d ago

Oh yeah, when working with external libraries it makes sense for sure. The idea of using data() to speed up debug builds is the surprising one. I'd use a release build with debug symbols first.

2

u/frnxt 7d ago

In general we're not modifying the lowlevel optimized parts of our framework very often (and it's often a task in itself to validate their correctness) and we mostly use the debug builds to debug issues in layers above that (which, honestly, could be written in Python with the "small" problem that Python is absolute shit at threading). You could argue we could split the lowlevel core in a separate library and just compile that one in release, but... small team and an old historical build system and all that.