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]
Lets start with defining both Temporal and Spatial Locality.
Temporal Locality - Temporal locality means current data or instruction that is being fetched may be needed soon. So we should store that data or instruction in the cache memory so that we can avoid again searching in main memory for the same data and thus saving time.
Spatial Locality - Spatial locality means instruction or data near to the current memory location that is being fetched, may be needed soon in near future.
sum = 0;
for (i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
Now looking at this example, Here variable sum is being used again and again which shows Temporal Locality and then the values of array arr is being accessed in order i.e arr[0], arr[1], arr[2] ,... and so on and which shows Spatial locality as arrays are Contiguous(adjacent) memory blocks so data near to current memory location is being fetched.
Now looking at this example
for(i = 0; i < 20; i++)
for(j = 0; j < 10; j++)
a[i] = a[i]*j;
Here we see temporal locality as a[i] in second loop is being used again and again and then variable j is being accessed in order which shows Spatial Locality.