简体   繁体   English

while(n> 0)和while(n!= 0)的评估之间的差异

[英]Difference between evaluation of while(n>0) and while(n!=0)

Is the evaluation of while(n>0) and while(n!=0) different? while(n>0)while(n!=0)的评估是否不同? Basically both are to exit in the same condition. 基本上两者都是以相同的条件退出。 So is there a scenario when one of them should be used? 那么是否应该使用其中一个? Or will it make a difference in the performance efficiency by changing the loop condition when the number of times the loop being evaluated being the same? 或者,当被评估的循环次数相同时,通过改变循环条件会对性能效率产生影响吗?

This depends on your platform, but in general, it will perform identically. 这取决于您的平台,但一般情况下,它将执行相同的操作。 For example, for x86 architecture cmp operator will be used for both > or != . 例如,对于x86架构, cmp运算符将用于>!= Here you can read more. 在这里你可以阅读更多。

除了条件不同之外,性能没有明显区别。

In general, the difference will be neutral. 一般来说,差异将是中性的。

Anyway, one could maliciously think of special schemes like 无论如何,人们可能会恶意地想到像这样的特殊方案

while (n > 0)
{
  ...
  n++;
}

vs.

while (n != 0)
{
  ...
  n++;
}

where the compiler can infer that in the first snippet the test needs to be done on the first iteration only, and unroll the while into an if . 编译器可以在第一个代码片段中推断出测试需要在第一次迭代时进行,并将while展开为if

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

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