Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for loop performance

What is better in for loop

This:

for(int i = 0; i<someMethod(); i++)
{//some code
 }

or:

int a = someMethod();
for(int i = 0; i<a; i++)
{//some code
 }

Let's just say that someMethod() returns something large.

First method will execute someMethod() in each loop thus decreasing speed, second is faster but let's say that there are a lot of similar loops in application so declaring a variable vill consume more memory.

So what is better, or am I just thinking stupidly.

like image 321
pedja Avatar asked Feb 04 '13 14:02

pedja


2 Answers

The second is better - assuming someMethod() does not have side effects.
It actually caches the value calculated by someMethod() - so you won't have to recalculate it (assuming it is a relatively expansive op).

If it does (has side effects) - the two code snaps are not equivalent - and you should do what is correct.

Regarding the "size for variable a" - it is not an issue anyway, the returned value of someMethod() needs to be stored on some intermediate temp variable anyway before calculation (and even if it wasn't the case, the size of one integer is negligible).

P.S.
In some cases, compiler / JIT optimizer might optimize the first code into the second, assuming of course no side effects.

like image 176
amit Avatar answered Oct 07 '22 18:10

amit


If in doubt, test. Use a profiler. Measure.

like image 38
PaulJWilliams Avatar answered Oct 07 '22 16:10

PaulJWilliams