Efficiency in accessing array elements

From: Davide (ppp_at_ppp.it)
Date: 04/30/04


Date: Fri, 30 Apr 2004 11:02:40 +0200

Hello,
this could be a trivial for question for you, anyway:

I have an hi-level code operation in which I need to access several times
the same element of an array, say A(K).
Is it -in general- more efficient to assign, at the beginning of the
operation, that element to a local variable (X:=A(K))
to be used in the rest of the operation instead of using each time A(K)?

Example:

VAR_1 := A(3) + A(5);
VAR_2 := A(3) - A(2);
VAR_3 := A(2) - A(5);
VAR_4 := A(3) * A(2);
....

is less efficient then:

A_2:= A(2);
A_3:= A(3)
A_5:= A(5)
VAR_1 := A_3 + A_5;
VAR_2 := A_3 - A_2;
VAR_3 := A_2 - A_5;
VAR_4 := A_3 * A_2;

?

Thank you.