Skip to content

Array Stride Access

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 11 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 AA of length nn and a stride ss, process indices:

0,s,2s,3s, 0, s, 2s, 3s, \dots

while the index remains less than nn.

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] A = [8, 3, 5, 1, 9, 4, 2]

and

s=2 s = 2

The scan visits:

stepindexvalue
108
225
349
462

Visited sequence:

[8,5,9,2] [8, 5, 9, 2]

Correctness

The algorithm starts at index 00 and adds ss after each access. Since s>0s > 0, the index increases monotonically. The loop condition ensures that every accessed index satisfies 0i<n0 \le i < n.

Thus the algorithm processes exactly the positions of the form ksks that lie inside the array.

Complexity

The number of visited elements is:

ns \left\lceil \frac{n}{s} \right\rceil
operationtime
stride scanO(n/s)O(n / s)
worst case, s=1s = 1O(n)O(n)

Space usage:

O(1) 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
}