Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPU overhead for struct?

Tags:

c++

c

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++;
like image 295
Znorg Avatar asked Mar 10 '14 20:03

Znorg


People also ask

Does struct have overhead?

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.

Do classes have overhead in C++?

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).

What is the scope of a struct?

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.

Are struct members contiguous in memory?

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.


1 Answers

"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
like image 196
Sam Cristall Avatar answered Sep 21 '22 11:09

Sam Cristall