Which is faster, access to a pointer or access to a link?

In the code example below, I highlight some instances of struct Chunk. In the for loops, I then iterate over the memory block and access various instances, using either a pointer or links, and assigning some random data to them.

But which cycle will be executed the fastest? According to my information, I would say that the reference cycle will be the fastest, because it does not require dereferencing and has direct access to the instance in memory. How am I wrong / right?

struct Chunk { unsigned int a; float b; const char* c; }; int main() { Chunk* pData = new Chunk[8]; for( unsigned int i = 0; i < 8; ++i ) { Chunk* p = &pData[i]; p->a = 1; p->b = 1.0f; p->c = "POINTERS"; } for( unsigned int i = 0; i < 8; ++i ) { Chunk& r = pData[i]; ra = 1; rb = 1.0f; rc = "REFERENCES"; } delete [] pData; return 0; } 
+6
source share
4 answers

They should be the same (not the same, but exactly the same) with any non-idiotic compiler. Under the hood, links are pointers (to 99% of compilers). There is no reason for any differences.

Pedantry: the second cycle may be faster (probably not), because the data is already in the cache, but that is. :)

+10
source

There should be no difference in the code created by any worthy compiler.

+1
source

If you doubt two versions of the code, similar to those indicated in your example, you should choose one of the more readable ones. The supposed optimization of your view should be done by the compiler.

More readable in your case is more likely a version with links (in fact, perhaps not very readable, but the consensus is to prefer using links, because pointers are more "dangerous").

But back to efficiency: (please, if someone knows assembler, better stop reading or you risk a laugh attack ...) In my opinion, since pData is on the heap, the compiler will have to compile it, using it anyway. I think that your reasoning may be correct if your structure was pushed onto the stack only with "Chunk data [8];". But, in the end, when the compiler optimization on the difference has to be removed anyway.

+1
source

I am tempted to say: who needs it? Any difference in speed will be negligible, and you should choose the most readable. In this particular case, I would expect to see exactly the same code generated in both cases. In more complex cases, the compiler may not determine later in the loop that the pointer has not been re-set, and you may have to reread it. But for this you will need to be doing enough other things that the difference will not be measurable.

+1
source

Source: https://habr.com/ru/post/925321/


All Articles