[H-GEN] Which is better?

Harry Phillips harry at tux.com.au
Sat Apr 24 04:12:54 EDT 2004


A bit of background: I started Uni this year and am doing COMP1500, it's a
course teaching Object oriented programing using Java.

I have a question about coding technique. I will give two examples and
would like to know if anyone knows which is more effcient or if they are
the same.

First code:
int arrayLen = myArray.length;
for (int i = 0; i < arrayLen; i++)
...


Second one:
for (int i = 0; i < myArray.length; i++)
...


I think the first would be more efficent since it does not have to
calculate the length of array "myArray" for each loop *then* make a
comparison to i. The first code only calculates the length once then makes
one comparision for each loop.

It may not be much different for array's that have a length that is small
but what about bigger arrays? What about when a method is used for the
calulation?

For example:

First code:
int upperLimit = doCalcs(variable);
for (i = 0; i < upperLimit; i++) {
....
}

public static int doCalcs(incoming int) { ...
<many many lines of code>
return xxx;
}


Second code:
for (i = 0; i < doCalcs(variable); i++) {
....
}

public static int doCalcs(incoming int) { ...
<many many lines of code>
return xxx;
}


In my mind the first would be many magnitudes faster since it only uses
the method "doCalcs" once, the second one would use the method for every
loop.

Or is Java more cleverer than I think and it knows that it will have to
use the calulation multiple times, does the calculation once (using the
method doCalcs) and uses an internal reference?

-- 
Harry Phillips




More information about the General mailing list