"Expensive" is a very relative term, especially with relationship to an "if" statement since you also have to take into the account the cost of the condition. That could range anywhere from a few short cpu instructions to testing the result of a function that calls out to a remote database.
你可以跳转到内存中任意位置的任意代码,如果它没有被 CPU 缓存——我们有一个问题,因为我们需要访问主存,这比较慢
现代 CPU 执行分支预处理。他们尝试猜测是否会成功,并在管道中提前执行代码,因此加快了速度。如果预测失败,那么流水线提前完成的所有计算都将失效。这也是一项昂贵的手术
总而言之:
如果可以是昂贵的,如果你真的,真的,真的关心性能。
You should care about it 如果,也只有如果 you are writing real time raytracer or biological simulation or something similar. There is no reason to care about it in most of the real world.
要执行的当前指令存储在通常称为 指令指针(IP)或 program counter(PC)的东西中; 这些术语是同义的,但不同的术语用于不同的体系结构。对于大多数指令,下一条指令的 PC 只是当前 PC 加上当前指令的长度。对于大多数 RISC 体系结构来说,指令的长度都是固定的,所以 PC 可以按固定的数量增加。对于像 x86这样的 CISC 架构,指令可以是可变长度的,因此解码指令的逻辑必须计算出当前指令需要多长时间才能找到下一条指令的位置。
Conditional vs. unconditional is easy to understand - a conditional branch is only taken if a certain condition holds (such as whether one number equals another); if the branch is not taken, control proceeds to the next instruction after the branch like normal. For unconditional branches, the branch is always taken. Conditional branches show up in if statements and the control tests of for and while loops. Unconditional branches show up in infinite loops, function calls, function returns, break and continue statements, the infamous goto statement, and many more (these lists are far from exhaustive).
The most expensive in terms of ALU usage? It uses up CPU registers to store the values to be compared and takes up time to fetch and compare the values each time the if statement is run.
Also note that inside a loop is 没有 necessarily very expensive.
现代 CPU 在第一次访问 if 语句时假定将采用“ if-body”(或者换一种说法: 它还假定将多次采用循环 body)(*)。经过第二次和进一步的访问,它(CPU)也许可以查看 分支历史表,看看上一次的情况如何(是真的吗?是假的吗?).如果上次为 false,那么 Speculative_execution 将继续执行 If 的“ else”,或者超出循环。
(*)规则实际上是“ 前面的树枝没拿走,后面的树枝拿走了”。在 if 语句中,如果条件的计算结果为 false (请记住: CPU 无论如何都假定不采用分支/跳转) ,那么 只有有一个[正向]跳转(到 在 if-body 之后点) ,但是在循环中,可能有一个前向分支到循环后的位置(不采用) ,并且在重复时有一个后向分支(采用)。
If else: if should be more likely and if there is a return that should be in else.
For and While should be replace by: do while -> except if there is a continue.
That continue should then become an: if do while -> in that order.
If it absolutely necessary to test at beginning use: if do while
If there is less than 5 cases switch to if else from most likely to least likely
Cases should be of relative likelihood, otherwise should be expressed as if else before switch.
Bitwise operators and better logical operators
“Simple integer operations such as addition, subtraction, comparison, bit operations and shift operations (and increment operators) take only one clock cycle on most microprocessors.”