[H-GEN] Which is better?

Paul Gearon pag at tucanatech.com
Mon Apr 26 23:26:19 EDT 2004


OK, lots of people have answered this already, probably more completely than I 
would have.  I agree with Greg and Andrae (ie. Harry, you don't want nor need 
to know), but like Andrae I too wanted to know all this stuff.  It helped fill 
in the picture in my head.  :-)

Harry Phillips wrote:
> 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.

Several people touched on this already, but I thought it might be worth 
pointing out explicitly...  The second code does *not* calculate the length of 
the array for each loop as you suggested.  Notice how myArray.length is not 
followed by a pair of parentheses?  That means that it's a field of the 
myArray object.  It's not calling a method on the object.

Incidentally, the length field for array objects is immutable.  That means 
that you can't change the length of that array.  It's possible for myArray to 
be set to a whole new object (which could have a different length), but the 
object it's pointing to can't be changed.  So long as the loop doesn't contain 
code like:
   myArray = new WhateverType[newLength];
then myArray.length will be constant.  It's easy for an optimiser to see this 
is happening.

-- 
Regards,
Paul Gearon

Software Engineer                Telephone:   +61 7 3876 2188
Tucana Technologies              Fax:         +61 7 3876 4899
                                  http://www.tucanatech.com

Catapultam habeo. Nisi pecuniam omnem mihi dabis, ad caput tuum saxum
immane mittam.
(Translation from latin: "I have a catapult. Give me all the money,
or I will fling an enormous rock at your head.")





More information about the General mailing list