什么通常更快:
if (num >= 10)
或:
if (!(num < 10))
最佳答案
编译器很可能会优化这类事情。别担心,在这种情况下只需编写代码以清楚起见。
汇编语言通常有 >=
的操作和 <=
与 <
的步数相同和 >
.例如,使用 Motorola 68k , 如果你想比较数据寄存器 %d0
和 %d1
和分支如果 %d0
大于或等于 %d1
,你会说这样的话:
cmp %d0, %d1 // compare %d0 and %d1, storing the result
// in the condition code registers.
bge labelname // Branch to the given label name if the comparison
// yielded "greater than or equal to" (hence bge)
认为 a >= b
是一个常见的错误意味着计算机将执行两个操作而不是一个操作,因为“大于或等于”中的“或”。
关于比较效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1430706/