简体   繁体   English

一元运算符和二进制运算符之间的性能差异

[英]Performance difference between unary and binary operator

Is there actually a performance difference between -foo and (-1)*foo where foo is a variable of type int ? -foo(-1)*foo之间实际上存在性能差异,其中fooint类型的变量吗? In theory the unary operator should be faster. 理论上,一元运算符应该更快。 But I think the compiler will optimise this out. 但是我认为编译器会对此进行优化。

Is there actually a performance difference between -foo and (-1)*foo -foo(-1)*foo之间实际上存在性能差异-foo

Theoretically there can be. 从理论上讲可以。 The C++ standard makes no guarantees either way. C ++标准对此不做任何保证。

However, assuming type of foo is an integer, then there is absolutely no difference between the observable behaviour of those expressions. 但是,假设foo类型是整数,则这些表达式的可观察行为之间绝对没有区别。 The compiler is therefore in that case allowed to generate an identical binary program for either expression. 因此,在这种情况下,允许编译器为每个表达式生成相同的二进制程序。 A ideal optimiser should generate the program that that performs better. 理想的优化程序应生成性能更好的程序。

Whether your real compiler generates the same output for both programs is another matter - no real compiler is ideal. 真正的编译器是否为两个程序生成相同的输出是另一回事-没有真正的编译器是理想的。 You can find out by using the compiler for both alternative programs and then comparing the output. 您可以通过使用两个替代程序的编译器,然后比较输出来找出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM