Posts Tagged ‘array’

A first simple optimisation

25 April 2008

As a very simple but safe code-movement optimisation, I have made my stage move calls to Array.length where the Array in question is stored in a final local variable out of loops. This is safe because once an array has been created its length cannot change, even though its contents may. As the reference is in a final local variable we are also guaranteed that the same array is indeed being referred to each time around the loop.

I have just realised that this is still not quite safe, as there could be a final local variable declared inside the scope of the loop, in which case it would be re-initialised (possibly to a different value) each time through the loop.

For example:

int j = 0;
while (j < 5) {
final int[] innerArray = new int[j];
System.out.println("innerArray length " + innerArray.length);
++j;
}

Here the value of innerArray.length will change on each iteration of the loop, even though innerArray is final.

Advertisements