Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

java - `if` condition efficiency

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The && operator (and also ||) is a short-circuit operator in Java.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...