Access array elements at regular intervals and understand the effect on locality.
Array stride access visits elements with a fixed step between consecutive indices. A stride of scans every element. Larger strides skip elements and may reduce cache locality.
You use it when data is sampled, stored in interleaved form, or traversed by columns in row-major storage.
Problem
Given an array of length and a stride , process indices:
while the index remains less than .
Algorithm
Scan with a fixed stride:
stride_scan(A, s):
if s <= 0:
error "stride must be positive"
i = 0
while i < length(A):
process A[i]
i += sExample
Let
and
The scan visits:
| step | index | value |
|---|---|---|
| 1 | 0 | 8 |
| 2 | 2 | 5 |
| 3 | 4 | 9 |
| 4 | 6 | 2 |
Visited sequence:
Correctness
The algorithm starts at index and adds after each access. Since , the index increases monotonically. The loop condition ensures that every accessed index satisfies .
Thus the algorithm processes exactly the positions of the form that lie inside the array.
Complexity
The number of visited elements is:
| operation | time |
|---|---|
| stride scan | |
| worst case, |
Space usage:
When to Use
Stride access is appropriate when:
- processing every kth element
- reading interleaved data
- sampling an array
- traversing columns in flat matrix storage
It is less suitable when sequential locality matters and all elements must be processed. In that case, prefer contiguous traversal.
Implementation
def stride_scan(a, stride, process):
if stride <= 0:
raise ValueError("stride must be positive")
i = 0
while i < len(a):
process(a[i])
i += stridefunc StrideScan[T any](a []T, stride int, process func(T)) bool {
if stride <= 0 {
return false
}
for i := 0; i < len(a); i += stride {
process(a[i])
}
return true
}