# is accessing an element in an array slower than accessing a variable?

when optimizing my code, i find myself often writing something like the following ...

do i = 1,n
r = t(i)
y(i) = r*r*2.0
f(i) = r*3.5
enddo


what i am doing with my variable, r is really irrelavent except that it is used more than once, and is most likely used as many as 5 or 6 times. now, in my head, i do this because i figure that accessing an array is slow and i want to store that variable so that i can retrieve it faster the next time. is this a correct line of thinking though? i wonder if, since i have used t(i), it is just as easy to reference in short succession as it is to reference r again. does storing a value from an array into a temporary variable make it quicker to us that value again, or is it just the same as if i had written

do i = 1,n
r = t(i)
y(i) = t(i)*t(i)*2.0
f(i) = t(i)*3.5
enddo


? if they are the same, then i am actually slowing things down by writing an extra assignment (r = t(i)).

• CPU dependent, compiler dependent, optimization level dependent, pipelining dependent, vectorization system dependent, the list just goes on and on. The days when you could look at a code and know how fast it would be have passed. – dmckee --- ex-moderator kitten May 18 '12 at 4:39
• Computational science does not preclude experimentation. As much as experimentalists are treated as distinct from computational scientists, we too have to formulate hypotheses and test them with experiments. Experiment with different equivalent ways of writing your code. Profile the code, and also instrument your code. (PETSc has some tools for this purpose; another such library is TAU.) The UNIX time command and the poor man's profiler are also useful. – Geoff Oxberry May 19 '12 at 7:48