英文:
What is faster to compute in C? (x==0) or (0==x)?
问题
In terms of translation, here are the relevant parts:
我想知道在C语言中哪种方式更好:
if (x==0)
{
// Some code ...
}
或者
if (0==x)
{
// Some code ...
}
从处理器的角度来看,计算时间。
通常情况下(不仅仅是针对AMD/Intel CPU,还包括不同处理器的嵌入式组件)。
我认为这与“lvalue”和“rvalue”有关,我尝试在我的PC上模拟,但没有明显的见解。
<details>
<summary>英文:</summary>
I wonder what is better to compute in C language:
```c
if (x==0)
{
// Some code ...
}
of
if (0==x)
{
// Some code ...
}
I know the last is better in case the programmer forgets the second "=" and write "0 = x" instead "0 == x" because the compiler will throw an error.
But my question is:
- From the processor's perspective, in compute time.
- In general (not just for AMD/Intel CPU, also for embedded components with different processors.
I think that related to "lvalue" and "rvalue", and I try to simulate in my PC, without significant insights.
答案1
得分: 5
没有通用的答案。实际的计算时间取决于目标系统、编译器及其优化。
如果你禁用所有优化,你可能会观察到生成了不同的机器代码,这可能导致不同的计算时间。
然而,现代编译器以许多方式优化你的代码。你可以期望这两种变体生成相同的机器代码。
为了确保对你的系统,编译这两种变体并查看生成的机器代码。正经的编译器有选项或工具可以生成列表。
结论: 如果你没有性能问题,不要过度优化。以最安全防范人为错误和最容易理解的方式编写代码。(顺便说一句,Yoda conditions 往往更难理解。)
术语“rvalue”在标准中只使用了两次,其中一次是在一个注释中:
> 有时被称为“rvalue”的东西在本文档中被描述为“表达式的值”。
第二次出现在索引中,指向这个注释。显然,它不再被使用。
等号操作符不区分它的操作数。两者都是相同种类的。
英文:
There is no general answer. The actual computing time depends on the target system and the compiler and its optimization.
If you disable all optimization, you might observe different machine code generated, and that could possibly have different computing time.
However, modern compilers optimize your code in many ways. You can expect that both variants generate the same machine code.
To be sure about your system, compile both variants and look at the generated machine code. Serious compilers have options or tools to produce a listing.
Conclusion: If you do not experience performance problems, do not micro-optimize. Write the source in the best way to be safe against human errors, and to be the easiest to understand. (BTW, Yoda conditions tend to be understood harder.)
The terms "rvalue" is only used twice in the standard, one time in a note:
> What is sometimes called "rvalue" is in this document described as the "value of an expression".
And the second time in the index, pointing to this note. Apparently it is not used any more.
The equality operator does not differentiate between its operands. Both are of the same kind.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论