[H-GEN] Which is better?

Benjamin benjamincarlyle at optusnet.com.au
Sat Apr 24 07:59:49 EDT 2004


On Sat, 24 Apr 2004 06:12 pm, Harry Phillips wrote:

> 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++)
> ...

Ok, this is me holding up the C++ flag:

for (vector<foo>::const_iterator it=bar.begin(); it!=bar.end(); ++it)
{
	...
}

:)
Can't you do something like that in Java? An iterator is a good concept in 
this scenario, since it can make the operation both clear and efficient. 
Usually the end() function refers to a simple member variable of the 
container so is low(-no) overhead to evaluate for each loop iteration. The 
lookup of *it may also be significantly more efficient (usually one 
operation) than doing one or more a[i] lookups (possibly several operations 
including a multiply and add) per loop iteration. Essentially by doing things 
the standard way you get the benefit of a lot of smart people already having 
thought about the performance implications, as well as being easy for others 
to read.

In short, do things the standard way. Understand the performance implications 
and deal with them if they're a problem, but doing things the standard way is 
by far the best default. The best you can do with your various options listed 
above are improving the constant in your algorithm. Most actual performance 
problems in software come from poor algorithm selection, which in turn often 
springs from poor data structure selection (including poor distributed 
algorithm and data structure selection). If you're really interested in 
improving the performance of your application get to know algorithms and data 
structures and always be sure that your data is being "looked at" only as 
many times as it needs to be. A well-performing application will almost 
always result despite the best efforts of inefficient language structures.

Benjamin.




More information about the General mailing list