Spatial vs. Temporal locality

raphnguyen picture raphnguyen · Sep 1, 2011 · Viewed 16k times · Source

I understand the definitions of the terms, but I am having trouble applying their concepts to code. For an exercise, we are asked to describe if the following code is spatial or temporal:

for (int i=0; i<10; i++) {
    printf(some_array[i]);
}

I feel like this is spatial locality because when one index of the array is accessed, the next index memory location will be accessed as soon as the loop iterates. Is this the correct way to look at it? What determines if code is temporal versus spatial? More examples would be great.

Answer

Oliver Charlesworth picture Oliver Charlesworth · Sep 1, 2011

It's a bit of a silly exercise, really. Code is not temporal or spatial.

But temporal locality implies that you're going to access the same address multiple times, relatively closely in time. You're not doing that here (unless you count accessing i, I guess), so by a process of elimination, you could conclude that this must be spatial locality.

More precisely, you're accessing some_array[0], then some_array[1], etc. etc. These are close together in address space, so yes, this may be "relying" on spatial locality.