C++ 常量正确性可以提高性能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3435026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:50:32  来源:igfitidea点击:

Can const-correctness improve performance?

c++performanceconst-correctness

提问by shuhalo

I have read numerous times that enforcing const-correctness in your C or C++ code is not only a good practice with regards to maintainability, but also it may allow your compiler to perform optimizations. However, I have read the complete opposite, too — that it does not affect performance at all.

我已经多次阅读到,在 C 或 C++ 代码中强制执行常量正确性不仅是关于可维护性的良好实践,而且还可以让您的编译器执行优化。然而,我也读到了完全相反的内容——它根本不影响性能。

Therefore, do you have examples where const correctness may aid your compiler with improving your program's performance?

因此,您是否有示例说明 const 正确性可以帮助您的编译器提高程序性能?

采纳答案by Billy ONeal

constcorrectness can't improve performance because const_castand mutableare in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your constdata may e.g. be a pointer to a std::atomic, meaning the compiler has to respect changes made by other threads.

const正确性不能提高性能,因为const_castmutable都在语言中,并且允许代码一致地违反规则。这在 C++11 中变得更糟,其中您的const数据可能例如是指向 a 的指针std::atomic,这意味着编译器必须尊重其他线程所做的更改。

That said, it is trivial for the compiler to look at the code it generates and determine if it actually writes to a given variable, and apply optimizations accordingly.

也就是说,编译器查看它生成的代码并确定它是否真的写入给定变量并相应地应用优化是微不足道的。

That all said, constcorrectness is a goodthing with respect to maintainability. Otherwise, clients of your class could break that class's internal members. For instance, consider the standard std::string::c_str()-- if it couldn't return a const value, you'd be able to screw around with the internal buffer of the string!

尽管如此,const正确性对于可维护性来说是一件好事。否则,您的类的客户端可能会破坏该类的内部成员。例如,考虑一下标准std::string::c_str()——如果它不能返回一个 const 值,你就可以使用字符串的内部缓冲区!

Don't use constfor performance reasons. Use it for maintainability reasons.

不要const出于性能原因使用。出于可维护性原因使用它。

回答by Praxeolitic

Yes it can.

是的,它可以。

Most consts are purely for the benefit of the programmer and do not help the compiler optimize because it's legal to cast them away and so they don't tell the compiler anything useful for optimization. However, some consts cannot be (legally) cast away and these do provide the compiler with useful information for optimization.

大多数consts 纯粹是为了程序员的利益,不会帮助编译器优化,因为丢弃它们是合法的,所以它们不会告诉编译器任何对优化有用的东西。但是,某些consts 不能(合法地)丢弃,这些确实为编译器提供了用于优化的有用信息。

As an example, access to a global variable defined with a consttype can be inlined while one without a consttype cannot be inlined because it might change at runtime.

例如,const可以内联对使用类型定义的全局变量的访问,而无法内联没有const类型的全局变量,因为它可能会在运行时更改。

https://godbolt.org/g/UEX4NB

https://godbolt.org/g/UEX4NB

C++:

C++:

int foo1 = 1;
const int foo2 = 2;

int get_foo1() {
    return foo1;
}

int get_foo2() {
    return foo2;
}

asm:

汇编:

foo1:
        .long   1
foo2:
        .long   2
get_foo1():
        push    rbp
        mov     rbp, rsp
        mov     eax, DWORD PTR foo1[rip] ; foo1 must be accessed by address
        pop     rbp
        ret
get_foo2():
        push    rbp
        mov     rbp, rsp
        mov     eax, 2 ; foo2 has been replaced with an immediate 2
        pop     rbp
        ret

In practical terms, keep in mind that while constcan improve performance, in most cases it won't or it will but the change will not be noticeable. The primary usefulness of constis not optimization.

实际上,请记住,虽然const可以提高性能,但在大多数情况下不会或会但变化不会很明显。的主要用途const不是优化。



Steve Jessop gives another example in his comment on the original question which brings up something worth mentioning. In a block scope, it's possible for a compiler to deduce if a variable will be mutated and optimize accordingly, regardless of const, because the compiler can see all uses of the variable. In contrast, in the example above, it's impossible to predict if foo1will be mutated since it could be modified in other translation units. I suppose a hypothetical sentient ultra-compiler could analyze an entire program and determine if it's valid to inline access to foo1... but real compilers can't.

Steve Jessop 在他对原始问题的评论中给出了另一个例子,其中提出了一些值得一提的问题。在块作用域中,编译器可以推断变量是否会发生变异并相应地优化,而不管const,因为编译器可以看到该变量的所有用途。相比之下,在上面的示例中,无法预测是否foo1会发生变异,因为它可以在其他翻译单元中进行修改。我想一个假设的有知觉的超级编译器可以分析整个程序并确定内联访问是否有效foo1......但真正的编译器不能。

回答by Anycorn

in my experience, no

根据我的经验,没有

For scalar variables, compiler is able to determine whenever the value is changed and perform necessary optimization itself.

对于标量变量,编译器能够确定值何时更改并自行执行必要的优化。

For array pointers, const correctness is no guarantee that values are really constant in presence of potential aliasing problems. Hence compiler can not use const modifier alone to perform optimizations

对于数组指针,const 正确性并不能保证在存在潜在别名问题的情况下值确实是恒定的。因此编译器不能单独使用 const 修饰符来执行优化

if you are looking optimization, you should consider __restrict__or special function modifiers/attributes: http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

如果您正在寻找优化,您应该考虑__restrict__或特殊功能修饰符/属性:http: //gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html