In C/C++, is there any CPU overhead for acessing struct members in comparison to isolated variables?
For a concrete example, should something like the first code sample below use more CPU cycles than the second one? Would it make any difference if it were a class instead of a struct? (in C++)
1)
struct S {
int a;
int b;
};
struct S s;
s.a = 10;
s.b = 20;
s.a++;
s.b++;
2)
int a;
int b;
a = 10;
b = 20;
a++;
b++;
There may be an overhead to access a member of the struct which is at a non-zero offset. It may not always be possible to optimise this away.
No. Not in C++, anyway. The only difference between a struct and a class in C++ is the default access to members. In a struct, the default access is public (for compatibility with C structs).
Scope of struct type definitions If only one function needs to know about a particular struct definition, then it should be defined inside that function, but if more than one function needs to know the definition, then it should be defined globally.
They will not necessarily be contiguous in memory. This is due to struct padding. then they most likely will not be. However, in your particular case, you will still likely get padding after gender , to realign the struct to 8 bytes.
"Don't optimize yet." The compiler will figure out the best case for you. Write what makes sense first, and make it faster later if you need to. For fun, I ran the following in Clang 3.4 (-O3 -S):
void __attribute__((used)) StructTest() {
struct S {
int a;
int b;
};
volatile struct S s;
s.a = 10;
s.b = 20;
s.a++;
s.b++;
}
void __attribute__((used)) NoStructTest() {
volatile int a;
volatile int b;
a = 10;
b = 20;
a++;
b++;
}
int main() {
StructTest();
NoStructTest();
}
StructTest
and NoStructTest
have identical ASM output:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
movl $10, -4(%ebp)
movl $20, -8(%ebp)
incl -4(%ebp)
incl -8(%ebp)
addl $8, %esp
popl %ebp
ret
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