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;
}
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With