Looping over arrays.  
Author Message
johndoe666_341





PostPosted: 2003-11-24 18:42:00 Top

java-programmer, Looping over arrays. Isn't it a waste of resources to loop over arrays this way:

for (i = 0; i < myArray.length; i ++) {
// do something
}

... as opposed to create a variable to hold the value of
myArray.length first, like so:

int len = myArray.length;
for (i = 0; i < len; i ++) {
// do something
}

This way the length of the array doesn't have to be recalculated on
every iteration? Or am I completely wrong?

TIA,

AJ
 
Christophe Vanfleteren





PostPosted: 2003-11-24 18:49:00 Top

java-programmer >> Looping over arrays. Marc Twain
>Isn't it a waste of resources to loop over arrays this way:
>
> for (i = 0; i < myArray.length; i ++) {
> // do something
> }
>
> ... as opposed to create a variable to hold the value of
> myArray.length first, like so:
>
> int len = myArray.length;
> for (i = 0; i < len; i ++) {
> // do something
> }
>
> This way the length of the array doesn't have to be recalculated on
> every iteration? Or am I completely wrong?
>
> TIA,
>
> AJ

The length of the array is not recalculated every time, since the length of
an array is known the moment it is created.
It wouldn't even be possible to recalculate, since length is a public int
field, and not a method.

So I would definitely go for the first version, since it is clearer to read.
The second version is good if the calculation of the length is an expensive
operation.

--
Regards,
Christophe Vanfleteren
 
Chris Uppal





PostPosted: 2003-11-24 20:00:00 Top

java-programmer >> Looping over arrays. Christophe Vanfleteren wrote:

> > for (i = 0; i < myArray.length; i ++) {
> > // do something
> > }

> The length of the array is not recalculated every time, since the length
> of an array is known the moment it is created.
> It wouldn't even be possible to recalculate, since length is a public int
> field, and not a method.

Actually, it's not a field either -- it's a (very very) nasty hack in the
compiler that fakes arrays having a field named "length". In compiling for the
JVM it gets translated into a special JVM bytecode that retrieves the size of
the array. Of course that bytecode is then subject to whatever kind of
optimisation the JVM does -- for instance the JIT (if there is one) could
replace the code with a variable.

For the OP: it is highly unlikely that it'd make much difference whichever way
you expressed it. Go with the one that's easiest to read. (There's nothing
wrong with considering such performance issues as a way of learning and
deepening your understanding, but when it comes to production code the general
advise about such optimisations is "don't".)

-- chris


 
 
johndoe666_341





PostPosted: 2003-11-25 1:29:00 Top

java-programmer >> Looping over arrays. > So I would definitely go for the first version, since it is clearer to read.
> The second version is good if the calculation of the length is an expensive
> operation.

Thanks!

AJ