Thursday, August 20, 2020

Passing struct and accessing member variable vs passing member variable directly, which is faster?

I had this argument with a colleague some years back. He said that passing a reference to a variable directly is faster than passing a reference to a struct and then accessing a member of that struct. So I checked the assembly:

struct S {int a; int b;};

void f(S& s){
     s.b++;
}
void g(int& x){
     x++;
}
 
I compiled this on godbolt with -O3 and this is what I get:
 
f(S&):
add DWORD PTR [rdi+4], 1
ret
 
g(int&):
add DWORD PTR [rdi], 1
ret
 
 
So the only difference is you're accessing rdi + 4 vs rdi. 
 
I googled this and apparently there's no extra cost for using a fixed displacement on any current microarchitecture except for instruction size. 

I suppose it might matter in terms of code size (as programmers, we're always trying to fit all our code into L1 cache), but then I'd have to check whether doing it this way might cause extra code to be generated somewhere else.

No comments:

Post a Comment