[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4296
  • Last Modified:

Java compiler "for loop / if statement" optmization

I have the following situation

boolean x=isX();
booleean y=isY();

for(){
  if(x){
     doA();
     if(y)
      doC();    
  }
  else{
    doB();
    if(y)
      doC();    
  }  
}

As you can see the result of the if statements is not dependand on the for loop and are known prior to the loop. I need to make sure the code runs as fast as possible. I can have my if statements outside of the loop and have several different for loops like this

if(x)
   if(y){
      for(){
       doA(); doC();
     }
   }else{
     for(){
       doA();
     }
  }
else
   if(y){
      for(){
       doB(); doC();
     }
   }else{
     for(){
       doB();
     }
   }    

This is messy and can get a lot more messier if I need to add another level of decision making.

My question basically is if java compiler will optimize the first code snippet not do the the logic branching for each loop iteration which will make the first code snippet to be as efficient as the second code snippet. I know that I can run some tests to check on this but I would like to find out for sure and that it is documented somewhere. I purposely ommit the information about our jdk version because I would like to find out the generic answer or the one that shows the differences between different compilers.

thanks



     
0
IBTLehman
Asked:
IBTLehman
  • 4
  • 3
  • 2
  • +2
4 Solutions
 
CEHJCommented:
>>this but I would like to find out for sure and that it is documented somewhere.

I'm not sure if it is documented.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Well, the second approach looks better to me. It is better designed because if the value of 'x' and 'y' don't change, then you should not check them multiple times inside the loop. However, if you put them inside the loop, Java will always check them instead of caching the result, because it is likely that the variables were modified by another method in another thread (if they are data-members of the class), etc.
0
 
IBTLehmanAuthor Commented:
These variables are method variables, so the thread issues does not apply in our case. The reason I want to use the first form is because the for loop is much bigger then in the pseudo code above and the level of decision making can increase with time.  I believe that having a single loop with if statements inside will make the code cleaner and more understandlable in the long run.
It is possible that the answer here that I cannot do what I want without paying the perfromance price but it would just make sens that today's super-smart compilers will take care of such optimization. And that is what I am trying to figure out.

thanks

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
>>And that is what I am trying to figure out.

The best and probably only reliable way to find that out is to inspect the bytecode that's produced, but then of course you have the little matter of JIT ...
0
 
mightyoneCommented:
this could be easily optimized:
using boolian algebra this would be


doC ()=xy  + x'y = y(x+x') = y(1)=y
doB ()=x'
doA ()=x
so:
for(){
   if(y) doC()
   if(x) doA();
      else doB();
}
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> I believe that having a single loop with if statements inside will make the code cleaner and more understandlable in
>> the long run

Not necessarily. It depends upon the logic. If the logic says: If this condition is true, run the loop x times. Then you would obviously put the loop inside the if (). However, if the if () condition is inside, I don't think the JVM will do any optimizations for you in skipping multiple checks to that if () because the condition there is the same (how does it know that the condition is still true without testing the value of the variable?).
0
 
mightyoneCommented:
btw i think checking on true or false is extremly quick compared to initing a for() loop
0
 
imladrisCommented:
Remember that the first objective is always to write readable, maintainable, working code.

That's not to say performance issues are ignored. You certainly should ensure that your overall design, the datastructures used and coding practices used are matched to your needs. It is to say that performance should not be your primary goal until you have achieved the first objective. If you can rearrange things in a way that you think will perform better, and still be clear code, great! But don't start writing awkward unrolled complicated if/else/loops until you're sure you need to.

Once you the first objective is met then, and only then, if, and only if, you have an actual performance problem, should you go in, preferably with a profiler, figure out where the bottlenecks are, and spend effort optimizing them. At that point, in order to achieve specific performance objectives, it is justifiable to modify specific sections of code to accomplish performance objectives at the expense of maintenance.

The reality is that with 3GHz machinery being the standard off the shelf hardware it is uncommon for the evaluation of variables in some loop to have any actual impact on perceivable performance. It is also, in practical reality, harder than you think to predict which bit of your program is going to be the actual bottleneck. There is little point in expending effort, and sacrificing maintainability, on some piece of code that isn't in the bottleneck.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> btw i think checking on true or false is extremly quick compared to initing a for() loop

Yup.
0
 
IBTLehmanAuthor Commented:
thank you for all your replies. The pseudo code I provided was meant to clearly illustrate the question and not to be taken literally. The actual code is a lot more involved and with its own dependacies. The decision making can go up to 3  - 4 levels which makes the number of possible for loop variations to double digits. The reason the performance is of paramaount importance here is because this code is the back-end for AJAX lookup that I am building. While I do appreciate every response, what I am really looking for is the answer to my question as oppose to offerings of alternative solutions.

0
 
mightyoneCommented:
ok:


best is write good code.

good code is quick and still readable,

always analyze your business logic prior to optimize java code
use the -server switch on calling java

if decision is based on simple combination of if do that else do this.
abstact your problem like e.g. i did and try to optimize on a boolian algebra way, you will wonder what is possible. and surplus

when finished use a codeanalyzer like e.g. findbugs

if you run into performance problem and only then start profiling your code and see where you loose your time
0
 
mightyoneCommented:
is this one done?
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now