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

9

u/TimelyTraffic8003 6d ago

This may come off as a stupid question, but here goes. I often hear people suggest using compiler explorer to read assembly output, but why not just use your installed C++ compiler?

29

u/AKostur 6d ago

Convenience. As I recall, the early compiler-explorer was just a quick webpage slapped on top of feeding the code through g++ to get the assembly.

Edit: and I get access to compilers from a large number of different versions, different compilers, different platforms.

15

u/No_Engineering_1155 6d ago

I think the main reason is, that you only want to see a short snippet of your code in assembly and the convenience is there, copy-pasta your code and see what comes out as assembly. You can easily swap between compilers without installing them. But maybe there are other folks with better explanation.

10

u/Selbstdenker 6d ago

You can certainly do that. Compiler explorer is just a very easy way to do that. You do not have to figure out how to call your compiler to get the assembly instead of binary output or which tiny part of the executable is the part which comes from your code and not the cruft the compiler adds to get you an executable program. It also helps you to understand the instructions and aligns your code with the resulting instructions.

2

u/conundorum 5d ago

Part convenience (Compiler Explorer dynamically recompiles when you edit the code, instead of forcing you to manually recompile and open the new file), and part flexibility (Compiler Explorer lets you choose between a wide range of compilers, and can run multiple compilers simultaneously; it makes it easy to compare compilers to each other, and/or check ones you don't have installed).