Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster, pointer access or reference access?

In the example code below I allocate some instances of the struct Chunk. In the for loops I then iterate through the memory block and access the different instances by using either pointer or references, and assign them some random data.

But which for loop will execute the fastest? By my knowledge I'd say the reference-loop will be the fastest because it will require no dereferencing and has direct access to the instance in memory. How wrong / right am I?

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];
        r.a = 1;
        r.b = 1.0f;
        r.c = "REFERENCES";
    }

    delete [] pData;
    return 0;
}
like image 351
Michael Mancilla Avatar asked Sep 13 '12 14:09

Michael Mancilla


1 Answers

They should be the same (not about the same, but exactly the same) with any non-idiotic compiler. Under the hood, references are pointers (on 99% of compilers). There's no reason for any difference.

Pedantic: the second loop could be faster (probably not) because the data is in the cache already, but that's it. :)

like image 151
Luchian Grigore Avatar answered Oct 12 '22 18:10

Luchian Grigore