`if`条件效率 [英] `if` condition efficiency
问题描述
我正致力于提高 Java
计划的性能。
在我改进了数据结构
和算法的复杂性之后,我正在尝试改进实现。我想知道在条件中如何使用 if
语句是否真的很重要。
I'm working on improving the performance of a Java
program.
After I've improved the data structures
and the algorithm's complexity, I'm trying to improve the implementation. I want to know if it really matters how I use the if
statement in condition.
编译器是否对待这些两个版本一样吗?它们的成本是否相同(如果我在 if
语句中有更多变量)?
Does the compiler treat these two versions the same? Do they cost the same (If I have much more variables inside the if
statement)?
if(a && b && c && d && e && f && g)
OR
if(a)
if(b)
if(c)
if(d)
if(e)
if(f)
if(g)
(在这个特定的项目中我并不关心可读性,我知道第二个是不太可读)
推荐答案
&&
运算符(以及 ||
)是短路 Java中的运算符。
The &&
operator (and also ||
) is a short-circuit operator in Java.
这意味着如果 a
是 false
,Java不评估 b
, c
, d
等,因为它已经知道整个表达式 a&& b&& c&& d&& e&& f&& g
将是 false
。
That means that if a
is false
, Java doesn't evaluate b
, c
, d
etc., because it already knows the whole expression a && b && c && d && e && f && g
is going to be false
.
所以没有任何东西可以获得将 if
写为一系列嵌套的 if
语句。
So there is nothing to be gained to write your if
as a series of nested if
statements.
优化性能的唯一好方法是使用分析器测量程序的性能,确定实际性能瓶颈的位置,并尝试改进代码的这一部分。通过检查代码和猜测进行优化,然后应用微优化通常不是一种有效的优化方法。
The only good way to optimize for performance is by measuring the performance of a program using a profiler, determining where the actual performance bottleneck is, and trying to improve that part of the code. Optimizing by inspecting code and guessing, and then applying micro-optimizations, is usually not an effective way of optimizing.
这篇关于`if`条件效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!