Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking condition in loop [duplicate]

Tags:

java

loops

I would like to ask more experienced developers about one simple, but for me not obvious, thing. Assume you have got such a code (Java):

for(int i=0; i<vector.size(); i++){
   //make some stuff here
}

I came across such statements very often, so maybe there is nothing wrong in it. But for me, it seems unnecessary to invoke a size method in each iteration. I would use such approach:

int vectorSize = vector.size();
for(int i=0; i<vectorSize; i++){
    //make some stuff here
}

The same thing here:

for(int i=0; i<myTreeNode.getChildren().size(); i++){
   //make some stuff here
}

I am definitely not an expert in programming yet, so my question is: Am I seeking a gap where the hedge is whole or it is important to take care of such details in professional code?

like image 478
guitar_freak Avatar asked Apr 25 '13 18:04

guitar_freak


1 Answers

A method invocation requires that the JVM does indeed do additional stuff. So what you're doing, at first view seems like an optimization.

However, some JVM implementations are smart enough to inline method calls, and for those, the difference will be nonexistent.

The Android programming guidelines for example always recommend doing what you've pointed out, but again, the JVM implementation manual (if you can get your hands on one) will tell you if it optimizes code for you or not.

like image 167
vlad-ardelean Avatar answered Oct 05 '22 06:10

vlad-ardelean