Dies hängt vom Compiler ab, aber mehrere bekannte Compiler werden von dieser expliziten Optimierung in Ihrem Code profitieren.
Zu diesem Beispielcode:
int getValue() {
return rand();
}
void testA() {
ptr1->ptr2->b = getValue();
ptr1->ptr2->b = getValue();
ptr1->ptr2->b = getValue();
}
void testB() {
struct pqr *ptr2 = ptr1->ptr2;
ptr2->b = getValue();
ptr2->b = getValue();
ptr2->b = getValue();
}
Sowohl GCC 6.3 und Clang 3.9.1 mit O3 wird diese Anordnung ähnlich produzieren:
testA():
mov rax, QWORD PTR ptr1[rip]
mov rbx, QWORD PTR [rax+8] // load
call rand
mov DWORD PTR [rbx], eax // store
mov rax, QWORD PTR ptr1[rip]
mov rbx, QWORD PTR [rax+8] // load
call rand
mov DWORD PTR [rbx], eax // store
mov rax, QWORD PTR ptr1[rip]
mov rbx, QWORD PTR [rax+8] // load
call rand
mov DWORD PTR [rbx], eax // store
testB():
mov rax, QWORD PTR ptr1[rip]
mov rbx, QWORD PTR [rax+8] // load
call rand
mov DWORD PTR [rbx], eax // store
call rand
mov DWORD PTR [rbx], eax // store
call rand
mov DWORD PTR [rbx], eax // store
Warum betrachten Sie nicht die generierte Assembly für beide Versionen? Siehst du einen Unterschied? –
Wohin weisen Sie Speicher zu, auf den 'pqr * ptr2' zeigen soll? – Lundin
Inwieweit könnte dies für die Antwort relevant sein? – Gerhardh