I was reading this question, I wanted to ask more about the code that he showed i.e
for(i = 0; i < 20; i++)
for(j = 0; j < 10; j++)
a[i] = a[i]*j;
The questions are,
- I understand temporal locality, I think that references to i and j should be temporal locality. Am I right?
- I also understand spatial locality, as the question I linked answers that references to a[i] should be spatial locality. Am I right?
The person said,
"The inner loop will call same memory address when accessing a[i] ten times so that's an example for temporal locality I guess. But is there spatial locality also in the above loop?"
I don't agree with his guess. As the references generated by a[i] should be spacial locality (They will be referencing the next element in the block). Am I right?
First off, references to
var
can be temporally local or spatially local not temporal locality, which is improper grammar. Minor point.Now, on to your questions.
The principle of Temporal locality states that two instructions reference the same location within a relatively short timeframe. For example, in the code given,
a[i]
is referenced frequently, with instructions likea[i] = a[i] * 2
anda[i] = a[i] * 3
being executed very close together. If we are looking at this scope, we could say that references toj
anda[i]
are temporally local. References toi
are also temporally local, becausei
is referenced every timea[i]
is. However, if the last line of the given code read something likea[j] = a[j] * j
, then references toi
would not be temporally local, at least in the scope of the inner loop[1].The principle of Spatial locality states that two instructions reference contiguous memory locations. References to
a[i]
are a good example of this, as one can assume (most of the time) thata[0]
anda[1]
will be next to each other in memory.The first two basically cover this, but the quoted text is correct, and the code also demonstrates spatial locality.
[1] - Generally, when you are talking about locality, it will be in the context of a given level in the memory hierarchy, whether it be RAM or the L1 cache or what have you. In all but the most limited sense, references to both
i
andj
are temporally local.