哪个更快:!=或< [英] Which is faster: != or <
问题描述
以下哪个更快?
for (int i = 0; i < n; ++i)
或
for (int i = 0; i != n; ++i)
我想知道是因为我不了解硬件,因此也不了解计算机如何看待<
与!=
.
I'm wondering because I don't understand hardware and thus don't understand how a computer looks at <
versus !=
.
推荐答案
对于基本类型,这两个操作都花费完全相同的时间,因为无论您要求哪个,它们实际上都是确定的.
For primitive types, both operations take the exact same amount of time since both are actually determined regardless of which you ask for.
简而言之,每当进行基本比较(<
<=
>
>=
==
或!=
)时,运算符的一侧都会被减去.然后,减法的结果用于设置许多标志,其中最重要的标志是Z
(零),N
(负)和O
(溢出).根据名称,您应该能够弄清楚每个标志代表什么.例如:如果减法的结果为零,则将设置Z
标志.因此,无论您要的是<=
还是!=
,处理器所要做的就是检查由于初始减法而已正确设置的所有标志.
In short, whenever you make a basic comparison, <
<=
>
>=
==
or !=
, one side of the operator is subtracted from the other. The result of the subtraction is then used to set a number of flags, the most important of which are Z
(zero), N
(negative), and O
(overflow). Based on the names, you should be able to figure out what each flag represents. Ex: if the result of subtraction is zero, than the Z
flag is set. Thus, whether you ask for <=
or !=
, all the processor is doing is checking the flags which have all been set appropriately as a result of the initial subtraction.
理论上,由于必须检查两个标志(Z和N)而不是一个标志(=
只是关心Z),因此<=
花费的时间 会更长一些.但这发生的程度很低,即使是微秒级的结果也很可能忽略不计.
Theoretically, <=
should take slightly longer since two flags (Z and N) must be checked instead of one (=
just cares about Z). But this happens on such a low level that the results are most likely negligible even on a microsecond scale.
如果您真的有兴趣,请阅读处理器状态寄存器.
If you're really interested, read up on processor status registers.
对于非原始类型(即类),它取决于关系运算符的实现.
For non-primitive types, i.e. classes, it depends on the implementation of the relational operators.
这篇关于哪个更快:!=或<的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!