M02 · Memory Model

Contiguous Storage, Addresses and Cache Locality

An array puts its elements side by side, so the address of any element is simple arithmetic and neighbours travel together through the cache. A linked list scatters its nodes and has to read each address from the previous node. Both traversals are O(n), yet they use memory very differently. This lesson explains how, with a simplified cache model you can step through.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M02 Memory Model · 5 of 5 lessons available

You will be able to

  • Compute an element address from a base address, an index and an element size.
  • Explain spatial and temporal locality and why caches move whole lines.
  • Compare traversing an array and a linked list in terms of line loads, using a stated model.
  • Describe internal and external fragmentation and how compacting collectors affect layout.
  • Say which built-in collections are contiguous in C#, Python, Java and C++.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Memory is a long row of numbered bytes; a byte's number is its address. An array of n elements of s bytes each occupies one block starting at some base address, so element i starts at

address(i) = base + i × s

That one multiplication is why indexing is O(1): no searching, no pointer to follow. A linked list stores each element in its own node together with the address of the next node. To reach element i you must read i addresses, one after another.

The lab places an array at teaching address 0x1000 and the list nodes at scattered addresses in a heap region from 0x2000. Addresses are chosen for readability; real ones are larger and random.

Caches move lines, not bytes

Main memory is far slower than the processor, so CPUs keep recently used memory in small, fast caches. Data moves between memory and cache in fixed-size lines (64 bytes on most current desktop and server processors). Two effects follow:

  • Spatial locality: reading one element brings its neighbours in with it. The next few array reads are then served from the cache.
  • Temporal locality: data used recently is likely to still be cached when it is used again.

Hardware prefetchers also notice sequential access and fetch ahead, which helps arrays further. Following next pointers defeats both: each node may sit on a different line, and the processor cannot even start the next load until the current one has delivered the address.

The teaching model in the lab

The lab uses a deliberately simple model so every step can be shown:

  • memory moves in lines of 16, 32 or 64 bytes, and an address belongs to line ⌊address ÷ line size⌋;
  • the cache holds 1 to 4 lines; on a miss, the least recently used line is evicted;
  • a list node is the value plus an 8-byte pointer, with no allocator headers.

It counts line loads, not time. Real CPUs have several cache levels, different sizes and associativity, prefetchers and out-of-order execution. The model shows why contiguous data tends to need fewer loads; it does not predict how much faster any program runs.

In the model, an array of n elements of s bytes needs exactly ⌈n·s ÷ line⌉ loads (when it starts on a line boundary, as in the lab). A list needs up to one load per node, depending on where the nodes landed.

Big O does not see this

Traversing an array and traversing a linked list are both O(n). Big O counts operations and ignores the cost of each memory access, so two O(n) loops can behave very differently in practice. That is not a flaw in Big O; it is a reminder to state the cost model you are using.

Fragmentation

The free slots between the list nodes in the lab hint at fragmentation:

  • External fragmentation: free memory is split into many small pieces, so a large request can fail (or need fresh memory) even though enough bytes are free in total.
  • Internal fragmentation: a block is larger than what was asked for, because of alignment, padding or the allocator's size classes.

Compacting garbage collectors (the .NET GC, and most JVM collectors) move live objects together, which removes external fragmentation and can even place objects allocated one after another next to each other. A list built in one go in such a runtime is often fairly compact; after many insertions and removals it tends to scatter. C and C++ allocators never move objects.

Language notes

  • C#: T[] and List<T> keep elements contiguous; for value types such as int the values themselves sit in the array. An array of a class type holds references, and the objects live elsewhere. LinkedList<T> allocates one LinkedListNode<T> object per element.
  • Python: a list is a contiguous array of references (in CPython, pointers to objects). The int objects themselves are scattered, so even a list behaves partly like linked data for its values. array.array, bytes, bytearray and NumPy arrays keep raw numbers contiguous.
  • Java: an int[] holds the numbers; ArrayList<Integer> holds references to Integer objects. The Java specification does not describe memory layout, but HotSpot stores array elements contiguously. LinkedList allocates a node object per element.
  • C++: std::vector, std::array and std::string are contiguous containers by the standard: &v[i] == v.data() + i. std::list and std::forward_list allocate every node separately; std::deque uses fixed-size blocks.

Common mistakes

  • Choosing a linked list for "fast insertion" when the program mostly traverses: finding the position is O(n) and pointer chasing is slow.
  • Treating a Python list of numbers as compact numeric storage.
  • Quoting a speed-up from a model or a micro-benchmark as if it held on every machine.

Edge cases

  • An array of references is contiguous in its references only; the objects can be anywhere.
  • Element sizes that do not divide the line size make some elements straddle two lines.
  • With a cache of one line, even the array misses whenever it crosses into a new line, and nothing else.

Worked practice

1. An int array (4-byte elements) starts at address 4096. Where does element 10 start?

Answer

4096 + 10 × 4 = 4136.

2. In the teaching model with 32-byte lines, how many line loads does a traversal of 20 four-byte elements need, starting at 4096?

Answer

20 × 4 = 80 bytes, which spans ⌈80 ÷ 32⌉ = 3 lines: 3 loads.

Summary

  • Contiguous storage makes addresses arithmetic and indexing O(1).
  • Caches move whole lines, so neighbouring data comes along for free; linked nodes forfeit that.
  • The lab's cache is a teaching model: it counts line loads and makes no timing claims.
  • Fragmentation is wasted space between or inside blocks; compacting collectors reduce it.
  • Contiguous built-ins: arrays, List<T>, ArrayList (references), std::vector; Python's list holds references, array.array holds values.

Full implementation

The teaching cache model in four languages, checked against one shared fixture of address streams (sequential, scattered, LRU eviction), plus each language's own layout guarantee: adjacent int[] elements in C#, a contiguous array.array buffer in Python, references in a Java ArrayList, and &v[i] == v.data() + i in C++.

using System.Runtime.CompilerServices;
 
namespace Bekadan.Dsa.Examples.Memory;
 
/// <summary>
/// Contiguous vs linked layout, and the Memory Lab's teaching cache model
/// (fixed-size lines, a few of them, least recently used evicted). The model is
/// for explaining locality, not for predicting real hardware.
/// </summary>
public static class ContiguousVsLinked
{
    /// <summary>Element i of an array starts at base + i * size.</summary>
    public static long[] ArrayAddresses(long baseAddress, int count, int elementSize)
    {
        var addresses = new long[count];
        for (int i = 0; i < count; i++)
        {
            addresses[i] = baseAddress + (long)i * elementSize;
        }
        return addresses;
    }
 
    /// <summary>A list's next address can only be read from the current node (0 = null).</summary>
    public static List<long> ListAddresses(long head, IReadOnlyDictionary<long, long> next)
    {
        var addresses = new List<long>();
        for (long node = head; node != 0;)
        {
            addresses.Add(node);
            node = next.GetValueOrDefault(node);
        }
        return addresses;
    }
 
    /// <summary>Line loads (misses) for a sequence of reads, in the teaching cache.</summary>
    public static int CountMisses(IEnumerable<long> addresses, int lineSize, int capacity)
    {
        var cache = new List<long>();  // least recently used first
        int misses = 0;
        foreach (long address in addresses)
        {
            long line = address / lineSize;
            int at = cache.IndexOf(line);
            if (at >= 0)
            {
                cache.RemoveAt(at);
                cache.Add(line);
            }
            else
            {
                misses++;
                if (cache.Count == capacity) cache.RemoveAt(0);
                cache.Add(line);
            }
        }
        return misses;
    }
 
    /// <summary>What C# itself guarantees, checked without unsafe code.</summary>
    public static void CheckLayout()
    {
        int[] values = new int[8];
        for (int i = 0; i < values.Length; i++)
        {
            Check(Unsafe.ByteOffset(ref values[0], ref values[i]) == i * sizeof(int), "int[] elements are adjacent");
        }
        var list = new LinkedList<int>([10, 20, 30]);
        LinkedListNode<int> second = list.First!.Next!;
        Check(second.Value == 20 && second.Previous == list.First, "every LinkedListNode is a separate object linked by references");
    }
 
    private static void Check(bool condition, string claim)
    {
        if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/ContiguousVsLinked.cs

"""Contiguous vs linked layout, and the Memory Lab's teaching cache model.
 
The model (fixed-size lines, a few of them, least recently used evicted) explains
locality; it does not predict real hardware.
"""
 
from array import array
from collections.abc import Iterable
 
 
def _check(condition: bool, claim: str) -> None:
    if not condition:
        raise AssertionError(f"Claim failed: {claim}")
 
 
def array_addresses(base: int, count: int, element_size: int) -> list[int]:
    """Element i of an array starts at base + i * size."""
    addresses = []
    for i in range(count):
        addresses.append(base + i * element_size)
    return addresses
 
 
def list_addresses(head: int, nxt: dict[int, int]) -> list[int]:
    """A list's next address can only be read from the current node (0 = None)."""
    addresses = []
    node = head
    while node != 0:
        addresses.append(node)
        node = nxt.get(node, 0)
    return addresses
 
 
def count_misses(addresses: Iterable[int], line_size: int, capacity: int) -> int:
    """Line loads (misses) for a sequence of reads, in the teaching cache."""
    cache: list[int] = []  # least recently used first
    misses = 0
    for address in addresses:
        line = address // line_size
        if line in cache:
            cache.remove(line)
            cache.append(line)
        else:
            misses += 1
            if len(cache) == capacity:
                cache.pop(0)
            cache.append(line)
    return misses
 
 
def check_layout() -> None:
    """What Python itself guarantees."""
    numbers = array("i", range(8))
    view = memoryview(numbers)
    _check(view.c_contiguous and view.nbytes == len(numbers) * numbers.itemsize, "array.array keeps raw numbers in one contiguous buffer")
    shared = object()
    refs = [shared, shared]
    _check(refs[0] is refs[1], "a list stores references: the same object can sit in two slots")

Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_contiguous_vs_linked.py

package dev.bekadan.dsa.memory;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
/**
 * Contiguous vs linked layout, and the Memory Lab's teaching cache model (fixed-size
 * lines, a few of them, least recently used evicted). Java exposes no addresses, and
 * the JVM decides object layout; the model explains locality, it predicts nothing.
 */
public final class ContiguousVsLinked {
    private ContiguousVsLinked() {
    }
 
    /** Element i of an array starts at base + i * size. */
    public static long[] arrayAddresses(long base, int count, int elementSize) {
        long[] addresses = new long[count];
        for (int i = 0; i < count; i++) {
            addresses[i] = base + (long) i * elementSize;
        }
        return addresses;
    }
 
    /** A list's next address can only be read from the current node (0 = null). */
    public static List<Long> listAddresses(long head, Map<Long, Long> next) {
        List<Long> addresses = new ArrayList<>();
        long node = head;
        while (node != 0) {
            addresses.add(node);
            node = next.getOrDefault(node, 0L);
        }
        return addresses;
    }
 
    /** Line loads (misses) for a sequence of reads, in the teaching cache. */
    public static int countMisses(long[] addresses, int lineSize, int capacity) {
        List<Long> cache = new ArrayList<>();   // least recently used first
        int misses = 0;
        for (long address : addresses) {
            long line = address / lineSize;
            int at = cache.indexOf(line);
            if (at >= 0) {
                cache.remove(at);
                cache.add(line);
            } else {
                misses++;
                if (cache.size() == capacity) cache.remove(0);
                cache.add(line);
            }
        }
        return misses;
    }
 
    /** An int[] holds the numbers; an ArrayList holds references to objects. */
    public static void checkLayout() {
        int[] values = {10, 20, 30};
        values[1] = 21;
        check(values[1] == 21, "an int[] element is the number itself");
        List<StringBuilder> refs = new ArrayList<>();
        StringBuilder shared = new StringBuilder("x");
        refs.add(shared);
        refs.add(shared);
        check(refs.get(0) == refs.get(1), "an ArrayList stores references: one object can sit in two slots");
    }
 
    private static void check(boolean condition, String claim) {
        if (!condition) {
            throw new AssertionError("Claim failed: " + claim);
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/ContiguousVsLinked.java

#pragma once
 
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <list>
#include <unordered_map>
#include <vector>
 
namespace bekadan::dsa::memory {
 
// Contiguous vs linked layout, and the Memory Lab's teaching cache model (fixed-size
// lines, a few of them, least recently used evicted). The model explains locality;
// it does not predict real hardware.
 
// Element i of an array starts at base + i * size.
inline std::vector<std::uint64_t> array_addresses(std::uint64_t base, int count, int element_size) {
    std::vector<std::uint64_t> addresses(static_cast<std::size_t>(count));
    for (int i = 0; i < count; ++i) {
        addresses[static_cast<std::size_t>(i)] = base + static_cast<std::uint64_t>(i) * static_cast<std::uint64_t>(element_size);
    }
    return addresses;
}
 
// A list's next address can only be read from the current node (0 = nullptr).
inline std::vector<std::uint64_t> list_addresses(std::uint64_t head, const std::unordered_map<std::uint64_t, std::uint64_t>& next) {
    std::vector<std::uint64_t> addresses;
    for (std::uint64_t node = head; node != 0;) {
        addresses.push_back(node);
        const auto it = next.find(node);
        node = it == next.end() ? 0 : it->second;
    }
    return addresses;
}
 
// Line loads (misses) for a sequence of reads, in the teaching cache.
inline int count_misses(const std::vector<std::uint64_t>& addresses, std::uint64_t line_size, std::size_t capacity) {
    std::vector<std::uint64_t> cache;  // least recently used first
    int misses = 0;
    for (const std::uint64_t address : addresses) {
        const std::uint64_t line = address / line_size;
        if (const auto at = std::find(cache.begin(), cache.end(), line); at != cache.end()) {
            cache.erase(at);
            cache.push_back(line);
        } else {
            ++misses;
            if (cache.size() == capacity) cache.erase(cache.begin());
            cache.push_back(line);
        }
    }
    return misses;
}
 
// What the standard guarantees: std::vector is a contiguous container; std::list is not.
inline void check_layout() {
    std::vector<int> v(8);
    for (std::size_t i = 0; i < v.size(); ++i) assert(&v[i] == v.data() + i);
    const std::list<int> nodes{10, 20, 30};  // one allocation per node; no address relationship is promised
    assert(*std::next(nodes.begin()) == 20);
}
 
}  // namespace bekadan::dsa::memory

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/contiguous_vs_linked.hpp

References