[H-GEN] Which is better?
Matthew Sellers
msellers at bigpond.com
Sat Apr 24 07:19:09 EDT 2004
On Sat, 24 Apr 2004 18:12:54 +1000
Harry Phillips <harry at tux.com.au> 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++)
> ...
I think you will find that the length of the array is not being calculated but
is something java already knows about the array. The efficiency difference
between the two of these should be negligable to nonexistent.
What is probably more important in this case is which is easier to understand.
The second piece of code makes it obvious that the loop will terminate at the
end of the array. The first piece of code allows for the possiblility that you
may want to manipulate arrayLen within the loop separately to the length of the
array (If this should be the case then the name of the variable would be
mischosen). Which is more appropriate depends on the situation, naturally.
> 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;
> }
>
Here you are correct. If there is no reason for doCalc to be evaluated for
each iteration of the loop then it should not be.
>
> 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?
Regardless of the intelligence of the compiler, it is better to do away with
inefficient algorithms when you see them.
Remember that the most important thing is to strike the balance between
efficiency and maintainability (sometimes the two goals coincide, but not
always). The weighting should go more in favour of maintainability in most
cases.
--
Matthew Sellers
More information about the General
mailing list