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.
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)
(In this specific project I don’t really care about readability, I know the second is less readable)
The
&&operator (and also||) is a short-circuit operator in Java.That means that if
aisfalse, Java doesn’t evaluateb,c,detc., because it already knows the whole expressiona && b && c && d && e && f && gis going to befalse.So there is nothing to be gained to write your
ifas a series of nestedifstatements.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.