srccode
srccode

Reputation: 751

Does pointer to pointer dereference has any performance impact?

Which program is better?

Does storing pointer reference in a local copy make a considerable difference if dereferencing is done often?

Program1:

void program1(){
for (int i =0; i<1000; i++)
    a[i] = ptr1->ptr2->ptr3->structure[i].variable;
}

Program2

void program2(){
int* local_copy = ptr1->ptr2;
for (int i =0; i<1000; i++)
   a[i] = local_copy->structure[i].variable;
}

Upvotes: 0

Views: 212

Answers (1)

Pepijn Kramer
Pepijn Kramer

Reputation: 12849

Small test : https://godbolt.org/z/Pesfsoq1z

Inner loop :

a[n] = ptr1->ptr2->ptr3->structure[n].variable;

Compiles to :

mov     rcx, qword ptr [rax + 32]
mov     qword ptr [rsp + 32], rcx
movups  xmm0, xmmword ptr [rax]
movups  xmm1, xmmword ptr [rax + 16]
movaps  xmmword ptr [rsp + 16], xmm1
movaps  xmmword ptr [rsp], xmm0
xor     ebx, ebx

And inner loop :

a[n] = p->structure[n].variable;

Compiles to :

mov     rcx, qword ptr [rax + 32]
mov     qword ptr [rsp + 32], rcx
movups  xmm0, xmmword ptr [rax]
movups  xmm1, xmmword ptr [rax + 16]
movaps  xmmword ptr [rsp + 16], xmm1
movaps  xmmword ptr [rsp], xmm0
xor     ebx, ebx

Which is the exact same assembly, so the answer to your question (for clang 15) is : It doesn't matter. (The compiler has spotted the invariants and optimized)

PS. I used unique pointers to not have memory leaks. It is a small overhead to pay

Upvotes: 2

Related Questions