In: Computer Science
Define spatial and temporal locality. Consider the following code:
for (i=0; i < 50; i++)
for (j =0; j < 30; j++)
a[i] = a[i] * j;
b. Give an example of temporal locality in the above code.
****This requires some effort so please drop a like if you are satisfied with the solution****
Spatial Locality:
Spacial locality is defined as the statement or instruction or data near to the memory address the is being accessed currently may be needed soon in future ....
in Spatial locality two instructions or statements refer to contiguous memory locations..
arrays are the best example of Spatial locality
a) In the above code, in the inner loop, in the statement a[i] = a[i] * j , the array locations a[0], a[1] ,a[2] are contiguous memory locations and are being accessed frequently so a[i] are examples of Spacial locality
Temporal Locality:
Temporal locality is defined as the current memory location that is being accessed or data being fetched might needed again soon in future...
in Temporal locality the same memory location is accessed many number of times frequently..
variables in a loop are good examples for temporal locality as they being accessed frequently
b) In the above code, in the inner loop, in statement a[i] = a[i] * j the variables i and j are accessed frequently or their memory locations are accessed frequently (number of times the loop runs) so they are the examples of temporal locality.