Array Stride Access
Access array elements at regular intervals and understand the effect on locality.
Array Stride Access
Array stride access visits elements with a fixed step between consecutive indices. A stride of $1$ 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 $A$ of length $n$ and a stride $s$, process indices:
$$ 0, s, 2s, 3s, \dots $$
while the index remains less than $n$.
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 += s
Example
Let
$$ A = [8, 3, 5, 1, 9, 4, 2] $$
and
$$ s = 2 $$
The scan visits:
| step | index | value |
|---|---|---|
| 1 | 0 | 8 |
| 2 | 2 | 5 |
| 3 | 4 | 9 |
| 4 | 6 | 2 |
Visited sequence:
$$ [8, 5, 9, 2] $$
Correctness
The algorithm starts at index $0$ and adds $s$ after each access. Since $s > 0$, the index increases monotonically. The loop condition ensures that every accessed index satisfies $0 \le i < n$.
Thus the algorithm processes exactly the positions of the form $ks$ that lie inside the array.
Complexity
The number of visited elements is:
$$ \left\lceil \frac{n}{s} \right\rceil $$
| operation | time |
|---|---|
| stride scan | $O(n / s)$ |
| worst case, $s = 1$ | $O(n)$ |
Space usage:
$$ O(1) $$
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 += stride
func 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
}