我将形容词“技术”用于表示语言行为/怪癖和编译器副作用,例如生成代码的性能。
为此,答案是:否(*)。 (*) 是“请查阅您的处理器手册”。如果您正在使用一些边缘案例 RISC 或 FPGA 系统,您可能需要检查生成了哪些指令以及它们的成本。但是,如果您使用几乎任何传统的现代架构,那么lt、eq、ne 和gt 之间的处理器级成本没有显着差异。
如果您使用的是边缘情况,您会发现!= 需要三个操作(cmp、not、beq)与两个(cmp、blt xtr myo) )。同样,在这种情况下,RTM。
在大多数情况下,原因是防御/强化,尤其是在使用指针或复杂循环时。考虑
// highly contrived example
size_t count_chars(char c, const char* str, size_t len) {
size_t count = 0;
bool quoted = false;
const char* p = str;
while (p != str + len) {
if (*p == '"') {
quote = !quote;
++p;
}
if (*(p++) == c && !quoted)
++count;
}
return count;
}
一个不太人为的例子是你使用返回值来执行增量,接受来自用户的数据:
#include <iostream>
int main() {
size_t len = 5, step;
for (size_t i = 0; i != len; ) {
std::cout << "i = " << i << ", step? " << std::flush;
std::cin >> step;
i += step; // here for emphasis, it could go in the for(;;)
}
}
试试这个并输入值 1、2、10、999。
你可以防止这种情况:
#include <iostream>
int main() {
size_t len = 5, step;
for (size_t i = 0; i != len; ) {
std::cout << "i = " << i << ", step? " << std::flush;
std::cin >> step;
if (step + i > len)
std::cout << "too much.\n";
else
i += step;
}
}
但你可能想要的是
#include <iostream>
int main() {
size_t len = 5, step;
for (size_t i = 0; i < len; ) {
std::cout << "i = " << i << ", step? " << std::flush;
std::cin >> step;
i += step;
}
}
还有一些对< 的约定偏见,因为标准容器中的排序通常依赖于operator<,例如,多个 STL 容器中的散列通过说来确定相等性
if (lhs < rhs) // T.operator <
lessthan
else if (rhs < lhs) // T.operator < again
greaterthan
else
equal
如果lhs 和rhs 是用户定义的类,则将此代码编写为
if (lhs < rhs) // requires T.operator<
lessthan
else if (lhs > rhs) // requires T.operator>
greaterthan
else
equal
实现者必须提供两个比较函数。于是<成为了受青睐的运营商。