在函数内部使用 const 和 static const 在速度上有区别吗?
Is there a difference in speed between using const and static const inside a function?
在 C 中,static const
和 const
之间有什么区别 在函数中?
例如,以给定的代码示例为例:
void print_int(int x) {
assert( x < 5 && x > -5 );
const int i[9] = {
-4, -3, -2, -1, 0, 1, 2, 3, 4
};
printf("%i", i[x + 4]);
}
int main() {
print_int( 1 );
return 0;
}
对战:
void print_int(int x) {
assert( x < 5 && x > -5 );
static const int i[9] = {
-4, -3, -2, -1, 0, 1, 2, 3, 4
};
printf("%i", i[x + 4]);
}
int main() {
print_int(1);
return 0;
}
如果我使用 static const
而不是 const
,生成的程序集是否会得到更好的优化,或者两个示例的输出是否相同?哦,这些示例假设所有优化都已关闭,因为编译器可以有效地优化两者以产生相同的输出。
Would the generated assembly be optimized better if I used static
const
instead of const
, or would the output be the same for both
examples?
不,汇编不会相同,至少假设 x86 ABI 和相应的 ISA。 static storage duration 的对象在程序启动前初始化。 自动存储持续时间 的对象在堆栈框架 中进行管理,即按函数实例化。如果编译器决定,它们也可以直接存储在 CPU 寄存器中。
这两个示例之间不会有显着的性能差异,因为 I/O printf()
函数最耗时。
在 C 中,static const
和 const
之间有什么区别 在函数中?
例如,以给定的代码示例为例:
void print_int(int x) {
assert( x < 5 && x > -5 );
const int i[9] = {
-4, -3, -2, -1, 0, 1, 2, 3, 4
};
printf("%i", i[x + 4]);
}
int main() {
print_int( 1 );
return 0;
}
对战:
void print_int(int x) {
assert( x < 5 && x > -5 );
static const int i[9] = {
-4, -3, -2, -1, 0, 1, 2, 3, 4
};
printf("%i", i[x + 4]);
}
int main() {
print_int(1);
return 0;
}
如果我使用 static const
而不是 const
,生成的程序集是否会得到更好的优化,或者两个示例的输出是否相同?哦,这些示例假设所有优化都已关闭,因为编译器可以有效地优化两者以产生相同的输出。
Would the generated assembly be optimized better if I used
static
const
instead ofconst
, or would the output be the same for both examples?
不,汇编不会相同,至少假设 x86 ABI 和相应的 ISA。 static storage duration 的对象在程序启动前初始化。 自动存储持续时间 的对象在堆栈框架 中进行管理,即按函数实例化。如果编译器决定,它们也可以直接存储在 CPU 寄存器中。
这两个示例之间不会有显着的性能差异,因为 I/O printf()
函数最耗时。