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;
}