struct的CPU开销?

Zno*_*org 6 c c++

在C/C++中,与隔离变量相比,访问struct成员是否有任何CPU开销?

举一个具体的例子,下面的第一个代码示例是否应该使用比第二个更多的CPU周期?如果它是一个类而不是一个结构,它会有什么不同吗?(在C++中)

1)

struct S {
    int a;
    int b;
};

struct S s;
s.a = 10;
s.b = 20;    
s.a++;
s.b++;
Run Code Online (Sandbox Code Playgroud)

2)

int a;
int b;
a = 10;
b = 20;
a++;
b++;
Run Code Online (Sandbox Code Playgroud)

Sam*_*all 8

"还没有优化." 编译器会为您找出最佳案例.首先写下有意义的内容,如果需要,可以在以后加快速度.为了好玩,我在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();
}
Run Code Online (Sandbox Code Playgroud)

StructTest并NoStructTest具有相同的ASM输出:

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
Run Code Online (Sandbox Code Playgroud)

  • @hivert 我实际上首先在 16 位 MCU 上运行它,并且在两种情况下也是相同的。我只是想人们会认出 x86。 (2认同)