声明静态变量性能
declare static variable performance
在 C Linux 中,我可以将变量声明为静态变量到函数中,它只初始化一次,每次 CPU 将再次看到该声明,它将被跳过,或全局声明
其中一个函数会有更好的性能?
void increase_x()
{
static int x =0;
x+=1;
}
static int x = 0 ;
void increase_x()
{
x+=1;
}
没有区别。您甚至可以在编译代码的反汇编差异中看到这一点:
< localstatic: file format elf64-x86-64
---
> globalstatic: file format elf64-x86-64
107c107
< 1131: 8b 05 dd 2e 00 00 mov 0x2edd(%rip),%eax # 4014 <x.0>
---
> 1131: 8b 05 dd 2e 00 00 mov 0x2edd(%rip),%eax # 4014 <x>
109c109
< 113a: 89 05 d4 2e 00 00 mov %eax,0x2ed4(%rip) # 4014 <x.0>
---
> 113a: 89 05 d4 2e 00 00 mov %eax,0x2ed4(%rip) # 4014 <x>
两个版本的运行时性能应该相同。
但是,在第一个片段中,x
仅在 increase_x
的主体中可见 - 程序的其余部分无法使用它的值。
您可以将 increase_x
更改为 return x
的新值:
int increase_x()
{
static int x = 0;
return x += 1;
}
不过,这取决于您打算如何使用 x
的值。
在 C Linux 中,我可以将变量声明为静态变量到函数中,它只初始化一次,每次 CPU 将再次看到该声明,它将被跳过,或全局声明
其中一个函数会有更好的性能?
void increase_x()
{
static int x =0;
x+=1;
}
static int x = 0 ;
void increase_x()
{
x+=1;
}
没有区别。您甚至可以在编译代码的反汇编差异中看到这一点:
< localstatic: file format elf64-x86-64
---
> globalstatic: file format elf64-x86-64
107c107
< 1131: 8b 05 dd 2e 00 00 mov 0x2edd(%rip),%eax # 4014 <x.0>
---
> 1131: 8b 05 dd 2e 00 00 mov 0x2edd(%rip),%eax # 4014 <x>
109c109
< 113a: 89 05 d4 2e 00 00 mov %eax,0x2ed4(%rip) # 4014 <x.0>
---
> 113a: 89 05 d4 2e 00 00 mov %eax,0x2ed4(%rip) # 4014 <x>
两个版本的运行时性能应该相同。
但是,在第一个片段中,x
仅在 increase_x
的主体中可见 - 程序的其余部分无法使用它的值。
您可以将 increase_x
更改为 return x
的新值:
int increase_x()
{
static int x = 0;
return x += 1;
}
不过,这取决于您打算如何使用 x
的值。