'Surviving the Release Version' 文章中的const 和 volatile章节让我想到编译器可以使用const关键字作为其优化工作的提示。
您是否知道编译器的其他一些优化提示或函数的设计原则,以便编译器可以将它们内联?
顺便说一句,您是否将原始类型函数参数声明为 const 或 const 引用(如void foo(const int i)
或void foo(const int& i)
)?
谢谢!
'Surviving the Release Version' 文章中的const 和 volatile章节让我想到编译器可以使用const关键字作为其优化工作的提示。
您是否知道编译器的其他一些优化提示或函数的设计原则,以便编译器可以将它们内联?
顺便说一句,您是否将原始类型函数参数声明为 const 或 const 引用(如void foo(const int i)
或void foo(const int& i)
)?
谢谢!
限定条件很少const
能帮助编译器优化您的代码。您可以在 Herb Sutter 的“不断优化?”中阅读更多关于为什么会出现这种情况的信息。
关于你的最后一个问题:一般来说,你应该更喜欢通过值传递那些复制起来很便宜的东西(比如基本类型对象——sint
和float
s 等等——以及小类类型对象),并通过 const 引用传递其他类型。这是一个非常普遍的规则,有很多警告和例外。
一旦您启用了一些优化,编译器就会注意到该参数i
永远不会被修改,因此无论您将其声明为int
还是声明const int
为生成的代码都无关紧要。
传递参数的const &
目的是避免不必要的复制。在小参数(一个机器字或更少)的情况下,这不会带来更好的性能,所以你不应该这样做。foo(int)
比 更有效foo(const int&)
。
There's no practical benefit to either form. If the type is less than a single machine word, take it by value. The other thing is that a modern compiler's semantic analysis is way above what const can and can't do, you could only apply optimizations if it was pre-compiled or your code was VERY complex. The article you linked to is several years old and the compiler has done nothing but improve massively since then.
我不认为编译器可以使用 const 关键字进行优化,因为在任何时候都可以抛弃 const 。
它更多的是为了正确而不是优化。
一些“通用编译器”的东西从我的脑海中浮出水面。
然而,所有这些都应该只来自广泛的分析例程,以便您知道实际需要优化的内容。一般来说,编译器非常擅长优化,而无需程序员提供太多提示。
If you look into the sources of Linux kernel or some such similar projects, you will find all the optimisation clues that are passed on to gcc (or whichever compiler is used). Linux kernel uses every feature that gcc offers even if it is not in the standard.
This page sums up gcc's extensions to the C language. I referred C here because const and volatile are used in C as well. More than C or C++, compiler optimization appears the focus of the question here.
I don't think the real purpose of const
has much to do with optimization, though it helps.
Isn't the real value in compile-time checking, to prevent you from modifying things you shouldn't modify, i.e. preventing bugs?
For small arguments that you are not going to modify, use call-by-value.
For large arguments that you are not going to modify, use either call-by-reference or passing the address (which are basically the same thing), along with const
.
For large or small arguments that you are going to modify, drop the const
.
BTW: In case it's news, for real performance, you need to know how to find the problems you actually have, by profiling. No compiler can do that for you.