Frage

I wanted to ask about spatial and temporal locality . If I am in a loop with a looping variable say i and I am traversing an array named arr[i], then when I access arr[i] then according to me it should be both temporal and spatial locality as first I would accesss i and find out what i is and then go to that index. I am doing two things here,

  1. Accessing i (Temporal locality).
  2. Accessing the address arr[i] (spatial locality).

Please tell me if I am right with this certain situation.
Thanks in advance.

War es hilfreich?

Lösung

Temporal locality: do things happen over a short period of time? If so, they have temporal locality. If not, they do not.

Spatial locality: are things located close together in space (i.e. memory)? If so, they have spatial locality. If not, they do not.

Note that when using these terms you need to specify what is local to what; in isolation, they hold little meaning.

The elements of arr will (assuming the commonly meant implementation of "array", i.e. data elements allocated in a contiguous block) have spatial locality with respect to each other. You don't know (at least from anything stated in the question) where i will be located with respect to arr, so you can't say if these objects exhibit spatial locality with respect to each other or not.

The statements accessing i and arr[i] happen one after another, so these exhibit temporal locality, assuming the work you do on each array element is cheap; with this assumption, the referencing of different elements of arr by subsequent iterations will also exhibit temporal locality. If, however, for each iteration of the loop you call some function that takes a long time in between accessing i and arr, it will no longer be true that these accesses exhibit temporal locality.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top