[H-GEN] Which is better?
Edwin Groothuis
edwin at mavetju.org
Sat Apr 24 23:23:45 EDT 2004
On Sat, Apr 24, 2004 at 06:12:54PM +1000, Harry Phillips wrote:
> [ Humbug *General* list - semi-serious discussions about Humbug and ]
> [ Unix-related topics. Posts from non-subscribed addresses will vanish. ]
>
> 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++)
> ...
It depends on what you do with the myArray in the loop :-)
If you don't modify it (size-wise), then the first one is best.
If you do modify it (size-wise), then the second one is best.
Also, using a for() loops vs a foreach() loop:
for (index=0;index<myArray.length;index++) {
data=myArray[i]
...
}
vs
foreach (myArray as index=>data) {
...
}
at the first one you can "skip" elements by increasing the index
in the loop, the second one does all of them. I prefer the second
notation (because it's cleaner with regarding to syntax), but it's
less flexible.
As usual: use the right tool for the job.
Edwin
--
Edwin Groothuis | Personal website: http://www.mavetju.org
edwin at mavetju.org | Weblog: http://weblog.barnet.com.au/edwin/
More information about the General
mailing list