Memory Lab · simulation 3 of 5

Contiguous array vs linked nodes

The same values traversed as an array and as a linked list, with teaching addresses and a simplified cache-line model that counts line loads.

The full explanation is in the lesson Contiguous storage, addresses and cache locality.

What to watch for

  • Array addresses are computed (base + i × size); list addresses must be read from the previous node.
  • One line load brings in several array neighbours; scattered nodes tend to need a load each.
  • Free chunks between the nodes are where fragmentation comes from.

In each language

C#
int[] and List<int> store ints inline; LinkedList<int> allocates one node object per element.
Python
A list stores references to objects; array.array keeps raw numbers contiguous.
Java
An int[] holds the numbers; ArrayList<Integer> holds references to Integer objects.
C++
std::vector and std::array are guaranteed contiguous; std::list allocates every node.

The programs

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