Перейти к содержанию

23. Паттерны

О главе

Цель: собрать из коллекций частей I–VII пять-шесть приёмов, которые встречаются в продакшн-коде постоянно, и для каждого показать цифрами, где он выигрывает, а где — нет. Разбираем: свою коллекцию «по правилам» (что даёт ICollection<T>, struct-enumerator, версия), LRU-кэш на индексах массива без аллокаций, trie против отсортированного массива, multimap, вторичные индексы (и как они портятся), границу API (что отдавать наружу: сам список, обёртку, копию, снимок, окно).

Опирается на: главу 5 — контракты интерфейсов. Главу 6 — шаблон foreach, struct-enumerator, версия. Главу 8 — List<T>, CollectionsMarshal.AsSpan. Главу 10 — Dictionary. Главу 12 — LRU на LinkedList. Главу 16 и 18 — неизменяемость и copy-on-write.

Лабораторная: 23-patterns/start — шесть опытов с предсказаниями (PREDICT) и два TODO: IntrusiveLru.MoveToFront (IntrusiveLru.cs) и Multimap.GetValues (Multimap.cs); final — результат; bench — четыре группы бенчмарков.

Стенд: Ubuntu 26.04, 2 ядра AMD EPYC Rome (виртуальная машина), рантайм 10.0.12, Workstation GC. Бенчмарки — два прогона --warmupCount 6 --iterationCount 20.

Лабораторная: как с ней работать

Лабораторная этой главы — 6 опытов в chapters/23-patterns/start/Program.cs и заготовки с TODO (IntrusiveLru.cs, Multimap.cs). Работаем в три захода; они отмечены в тексте плашками «Предскажите» и «Задание» — там, где прочитан нужный материал:

  1. Предсказать и сверить. Перед опытом в тексте стоит плашка «Предскажите»: она называет строки start с меткой PREDICT. Впишите ответ в комментарий до запуска. Расхождение ответа и вывода — это то, что нужно объяснить; разбор — ниже по тексту.
  2. Дописать код. В файлах с TODO реализуйте метод по подсказке в комментарии; проверка — вывод опыта, названный в плашке «Задание». Не получилось — сверьтесь с final/.
  3. Сравнить с final (после того как сделали сами): откройте файлы final/ и найдите отличия от вашего start.

Плашки «Предскажите» и «Задание» означают «остановитесь и сделайте». Листинги final/… без плашки — для чтения и сравнения. Пути — от корня репозитория, команды — из папки chapters.

Чем start отличается от final.

start/ final/
Назначение то, что вы предсказываете и правите эталон и дополнительные опыты
Файлы с TODO IntrusiveLru.cs, Multimap.cs реализации
Одинаковые файлы ClassicLru.cs, Order.cs, OrderStore.cs, Program.cs, RingCollection.cs, RingEnumerable.cs, SortedWords.cs, Team.cs, Trie.cs менять не нужно

Запуск (из папки chapters): dotnet run -c Release --project 23-patterns\start, затем dotnet run -c Release --project 23-patterns\final.

23.1. Своя коллекция: что даёт ICollection<T>

Кольцевой буфер фиксированной ёмкости (при переполнении затирается самый старый элемент) в двух видах. Первый — минимум: только IEnumerable<T> через yield. Второй — «по правилам»: ICollection<T> + IReadOnlyList<T>, struct-enumerator с проверкой версии.

chapters/23-patterns/final/RingCollection.cs
public sealed class RingCollection<T>(int capacity) : ICollection<T>, IReadOnlyList<T>
{
    readonly T[] _items = new T[capacity];
    int _head, _count, _version;

    public int Count => _count;
    bool ICollection<T>.IsReadOnly => false;

    public T this[int index]
    {
        get
        {
            if ((uint)index >= (uint)_count) throw new ArgumentOutOfRangeException(nameof(index));
            return _items[(_head + index) % _items.Length];
        }
    }

    public void Add(T item)
    {
        if (_count < _items.Length) _items[(_head + _count++) % _items.Length] = item;
        else { _items[_head] = item; _head = (_head + 1) % _items.Length; }
        _version++;
    }

    public void Clear()
    {
        Array.Clear(_items);
        _head = _count = 0;
        _version++;
    }

    public bool Contains(T item)
    {
        var cmp = EqualityComparer<T>.Default;
        for (int i = 0; i < _count; i++)
            if (cmp.Equals(_items[(_head + i) % _items.Length], item)) return true;
        return false;
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        ArgumentNullException.ThrowIfNull(array);
        ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
        if (array.Length - arrayIndex < _count) throw new ArgumentException("Массив мал.", nameof(array));
        int first = Math.Min(_count, _items.Length - _head);
        Array.Copy(_items, _head, array, arrayIndex, first);
        Array.Copy(_items, 0, array, arrayIndex + first, _count - first);
    }

    // Удаление из середины кольца не поддерживаем — контракт ICollection<T> допускает NotSupportedException.
    bool ICollection<T>.Remove(T item) => throw new NotSupportedException();

    public Enumerator GetEnumerator() => new(this);
    IEnumerator<T> IEnumerable<T>.GetEnumerator() => new Enumerator(this);
    IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);

    public struct Enumerator : IEnumerator<T>
    {
        readonly RingCollection<T> _ring;
        readonly int _version;
        int _index;
        T _current;

        internal Enumerator(RingCollection<T> ring)
        {
            _ring = ring;
            _version = ring._version;
            _index = 0;
            _current = default!;
        }

        public T Current => _current;
        object? IEnumerator.Current => _current;

        public bool MoveNext()
        {
            if (_version != _ring._version) throw new InvalidOperationException("Коллекция изменена во время перечисления.");
            if (_index >= _ring._count) return false;
            _current = _ring[_index++];
            return true;
        }

        public void Reset() { _index = 0; _current = default!; }
        public void Dispose() { }
    }
}
  • Строка 5: оба интерфейса сразу. Публичное свойство Count реализует ICollection<T>.Count и IReadOnlyCollection<T>.Count; индексатор — IReadOnlyList<T>.
  • Строка 11: IsReadOnly — явная реализация, наружу не торчит.
  • Строки 44–52: CopyTo — два Array.Copy по сегментам кольца. Именно им пользуются ToArray() и new List<T>(source), когда источник — ICollection<T> (глава 14).
  • Строка 55: Remove из середины кольца не поддерживаем — контракт ICollection<T> разрешает NotSupportedException, но это надо документировать.
  • Строки 57–59: публичный GetEnumerator() возвращает struct (для foreach по типу), интерфейсные — боксируют его (глава 6).
  • Строки 61–88: enumerator запоминает _version и проверяет её в MoveNext.
   только IEnumerable: ToArray   4064 Б, ToList   8464 Б, Count()   40 Б
   ICollection<T>:     ToArray   4024 Б, ToList   4056 Б, Count()    0 Б
   TryGetNonEnumeratedCount: только IEnumerable = False, ICollection<T> = True (1000)
   изменение при обходе: InvalidOperationException

Предскажите: опыт 1

В chapters/23-patterns/start/Program.cs — строки 45–46 (метка PREDICT): во сколько раз различаются байты ToArray()/ToList() у буфера только с IEnumerable и у буфера с ICollection? Что делает Count()?

Впишите ответ в комментарий до запуска, затем выполните dotnet run -c Release --project 23-patterns\start (вывод опыта начинается с заголовка == Опыт 1.) и сверьтесь с разбором ниже.

Опыт 1 (final, 1000 элементов).

1000 элементов только IEnumerable<T> ICollection<T>
ToList() 5,6 мкс, 8 424 Б 0,44 мкс, 4 056 Б
ToArray() 7,0 мкс, 4 064 Б 0,35–0,42 мкс, 4 024 Б
Count() 4,4–4,5 мкс 0,25–0,37 нс
foreach 4,4–4,6 мкс 4,4–4,6 мкс

Бенчмарки (два прогона), 1000 элементов. На 10 элементах: ToList 105–109 против 39–41 нс, ToArray 138–153 против 24–26 нс, Count() 42 нс против 0,2–0,4.

Что видно:

  • ICollection<T> — это не «полнота» интерфейса, а три быстрых пути в BCL: Count без обхода (Count() в 10 000 раз быстрее), CopyTo вместо перечисления для ToArray/ToList/List<T>(IEnumerable) (12–20×), точная ёмкость при копировании (список от IEnumerable<T> растёт удвоением: 8 424 Б против 4 056).
  • foreach не выиграл: на горячем бенчмарке и struct-enumerator, и интерфейсный путь дают одно и то же и 0 Б — профиль мономорфный, JIT устранил бокс (так же, как в главе 6). В самом опыте 1 после двух вызовов (ещё Tier0) интерфейсный обход стоит 40 Б.
  • yield в самой коллекции — не бесплатно: Count_EnumerableOnly на 1000 элементах 4,4 мкс ≈ 4,4 нс на элемент: итератор yield плюс % в индексации кольца (замер вне лабораторной: суммирование по кольцу из 1024 int с индексацией (head + i) % a.Length — 4,4 нс на элемент, с маской & (n − 1) — 0,8 нс, то есть деление даёт ≈ 3,6 из 4,4 нс; при ёмкости — степени двойки % заменяют маской, см. практикум).

Факт: в ICollection<T> можно не реализовывать всё

Remove бросает NotSupportedException, а Add затирает старое — контракт это допускает, пока IsReadOnly и документация согласованы. Но реализация IList<T> «наполовину» ломает код, который проверяет IsReadOnly/IsFixedSize (глава 5); в этом буфере IsReadOnly = false — и Add действительно работает.

Если коллекция только читаемая, достаточно IReadOnlyList<T>, но быстрые пути LINQ смотрят именно ICollection<T> (Count() не использует IReadOnlyCollection<T>, глава 5): реализуйте оба, как здесь, если хотите и ту, и другую выгоду.

23.2. LRU-кэш: узлы на индексах массива

Глава 12 сравнивала LRU на LinkedList и на списке. Здесь — вариант без узлов-объектов: ключи, значения и ссылки «prev/next» — четыре параллельных массива фиксированной ёмкости, а Dictionary<TKey, int> отдаёт индекс слота.

Задание: реализуйте MoveToFront

В chapters/23-patterns/start/IntrusiveLru.cs — TODO 1 (строка 80): вынуть узел i из списка и поставить в голову.

Сделайте это до того, как смотреть решение в листинге ниже. Опыт 2 должен показать «расхождений: 0», опыт 4 — 0 байт.

chapters/23-patterns/final/IntrusiveLru.cs
public sealed class IntrusiveLru<TKey, TValue> where TKey : notnull
{
    readonly Dictionary<TKey, int> _map;
    readonly TKey[] _keys;
    readonly TValue[] _values;
    readonly int[] _prev, _next;
    int _head = -1, _tail = -1, _count;

    public IntrusiveLru(int capacity)
    {
        _map = new(capacity);
        _keys = new TKey[capacity];
        _values = new TValue[capacity];
        _prev = new int[capacity];
        _next = new int[capacity];
    }

    public int Count => _count;

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out int i))
        {
            MoveToFront(i);
            value = _values[i];
            return true;
        }
        value = default!;
        return false;
    }

    public void Set(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out int i))
        {
            _values[i] = value;
            MoveToFront(i);
            return;
        }
        if (_count < _keys.Length) i = _count++;
        else
        {
            i = _tail;                 // вытесняем самого давнего, его слот переиспользуем
            _map.Remove(_keys[i]);
            Unlink(i);
        }
        _keys[i] = key;
        _values[i] = value;
        _map[key] = i;
        PushFront(i);
    }

    public IEnumerable<TKey> KeysMostRecentFirst()
    {
        for (int i = _head; i >= 0; i = _next[i]) yield return _keys[i];
    }

    void Unlink(int i)
    {
        int p = _prev[i], n = _next[i];
        if (p >= 0) _next[p] = n; else _head = n;
        if (n >= 0) _prev[n] = p; else _tail = p;
    }

    void PushFront(int i)
    {
        _prev[i] = -1;
        _next[i] = _head;
        if (_head >= 0) _prev[_head] = i;
        _head = i;
        if (_tail < 0) _tail = i;
    }

    void MoveToFront(int i)
    {
        if (_head == i) return;
        Unlink(i);
        PushFront(i);
    }
}
  • Строки 7–20: словарь ключ → индекс слота, а не ключ → узел, и четыре массива одной ёмкости.
  • Строки 44–50: при переполнении переиспользуется слот хвоста — вытесняемый ключ удаляется из словаря, на его место пишется новый; ни одного нового объекта.
  • Строки 62–84: Unlink/PushFront/MoveToFront — обычный двусвязный список, только указатели — int, -1 — «нет».

Классический вариант (Dictionary + LinkedList<(K, V)>, chapters/23-patterns/final/ClassicLru.cs:5–43) выделяет LinkedListNode (48 Б) на каждую вставку.

   расхождений порядка/значений: 0, попаданий 4428 и 4428
   память на запись при 100,000: на индексах 37.7 Б, Dictionary+LinkedList 78.4 Б
   промахи (10 000 Set новых ключей): на индексах 0 Б, LinkedList 480000 Б

Предскажите: опыт 2

В chapters/23-patterns/start/Program.cs — строка 76 (метка PREDICT): порядок вытеснения совпадёт у обеих реализаций? Сколько байт на запись и на промах?

Впишите ответ в комментарий до запуска, затем выполните dotnet run -c Release --project 23-patterns\start (вывод опыта начинается с заголовка == Опыт 2.) и сверьтесь с разбором ниже.

Опыт 2 (final).

10 000 операций, 80 % попаданий время аллокации
Dictionary + LinkedList 655–725 мкс 99 600 Б
на индексах массива 267–277 мкс 0 Б

Бенчмарки, ёмкость 1024, два прогона.

Итог: в 2,4–2,6 раза быстрее, вдвое компактнее (37,7 против 78,4 Б на запись) и без нагрузки на GC. Плата: ёмкость задана заранее (массивы не растут) и код сложнее — отсюда обязательная сверка с эталоном (опыт 2 прогоняет 20 000 случайных операций и сравнивает порядок и значения).

Факт: аллокации — около трети разрыва

Обе версии делают по одному поиску в словаре на операцию. Разница — new LinkedListNode на каждый промах (48 Б, 20 % операций: 99 600 Б на 10 000 операций). Но не только она: вариант на LinkedList с переиспользованием вытесняемого узла (ClassicReuse в LruBench, два прогона) — 538–551 мкс против 683–697 мкс с new и 269–273 мкс на индексах. Аллокации объясняют ≈ 145 из ≈ 415 мкс разрыва; остальное — сами операции со связным списком (Remove/AddFirst на каждое попадание) и, вероятно, раскладка узлов в памяти (глава 11); счётчики кэша на ВМ недоступны.

23.3. Trie или отсортированный массив

Задача: 100 000 слов (3–10 строчных латинских букв), нужно «сколько слов начинается на abc» и «есть ли слово».

chapters/23-patterns/final/Trie.cs
public sealed class Trie
{
    sealed class Node
    {
        public Dictionary<char, Node>? Next;
        public int Pass;      // сколько слов проходит через узел (включая закончившиеся в нём)
        public bool End;
    }

    readonly Node _root = new();
    public int Count => _root.Pass;

    public bool Add(string word)
    {
        if (Contains(word)) return false;
        var node = _root;
        node.Pass++;
        foreach (char c in word)
        {
            node.Next ??= new();
            if (!node.Next.TryGetValue(c, out var child)) node.Next[c] = child = new();
            node = child;
            node.Pass++;
        }
        node.End = true;
        return true;
    }

    public bool Contains(string word) => Find(word) is { End: true };

    public int CountWithPrefix(string prefix) => Find(prefix)?.Pass ?? 0;

    public IEnumerable<string> WithPrefix(string prefix)
    {
        var node = Find(prefix);
        if (node is null) yield break;
        var stack = new Stack<(Node Node, string Text)>();
        stack.Push((node, prefix));
        while (stack.Count > 0)
        {
            var (n, text) = stack.Pop();
            if (n.End) yield return text;
            if (n.Next is null) continue;
            foreach (var (c, child) in n.Next) stack.Push((child, text + c));
        }
    }

    Node? Find(ReadOnlySpan<char> s)
    {
        var node = _root;
        foreach (char c in s)
            if (node.Next is null || !node.Next.TryGetValue(c, out node)) return null;
        return node;
    }
}
  • Строки 7–12: узел — Dictionary<char, Node> потомков (лениво), счётчик Pass — сколько слов проходит через узел, флаг End.
  • Строка 35: CountWithPrefix — O(длина префикса), без обхода поддерева: ответ лежит в счётчике узла.

Конкурент — отсортированный массив строк и две двоичные границы (chapters/23-patterns/final/SortedWords.cs:4–36): первый элемент ≥ префикса и конец блока с этим префиксом; память — только массив ссылок.

   слов 100,000/100,000. Память поверх самих строк: массив 787 КБ, trie 74134 КБ, HashSet 2121 КБ
   CountWithPrefix × 2000: trie 136–179 мкс, массив 841–1088 мкс (грубый замер в самом опыте)
   Contains × 100,000: trie 39 мс, HashSet 3,3 мс

Предскажите: опыт 3

В chapters/23-patterns/start/Program.cs — строка 115 (метка PREDICT): что компактнее и что быстрее на 100 000 слов — trie или массив + двоичный поиск?

Впишите ответ в комментарий до запуска, затем выполните dotnet run -c Release --project 23-patterns\start (вывод опыта начинается с заголовка == Опыт 3.) и сверьтесь с разбором ниже.

Опыт 3 (final).

1000 операций trie отсортированный массив HashSet<string>
CountWithPrefix 42–46 мкс 497–522 мкс —
Contains 143–152 мкс — 15–20 мкс
память поверх строк 74 МБ (≈ 740 Б/слово) 0,8 МБ 2,1 МБ

Что видно:

  • Префиксные запросы: trie в ≈ 11 раз быстрее (42–46 против 497–522 нс на запрос) — асимптотика (O(|p|) против O(|p| · log n)) здесь работает.
  • Память: trie с Dictionary<char, Node> в каждом узле — в 90 раз больше массива. Пустой Dictionary — 80 Б, плюс массивы bucket'ов и entry при первой вставке (глава 21); у большинства узлов 1–3 потомка.
  • Точный поиск: HashSet в 7–10 раз быстрее trie — за префиксом в trie тянется цепочка из обращений к словарям.

Вывод: trie — не «лучше хэш-таблицы», а ответ на префиксный запрос с частыми повторами. Если слова меняются редко, отсортированный массив + двоичный поиск даёт почти ту же возможность за 1 % памяти; если нужен точный поиск — HashSet. Если trie всё-таки нужен, сначала заменяют Dictionary<char, Node> на отсортированный маленький массив пар (см. практикум).

23.4. Multimap

Один ключ — много значений. Типовая ловушка — Dictionary<K, List<V>> в каждом месте кода со своей логикой «а если ключа нет».

Задание: реализуйте GetValues

В chapters/23-patterns/start/Multimap.cs — TODO 2 (строка 33): вернуть окно на список без аллокаций; для отсутствующего ключа — пустое окно.

Сделайте это до того, как смотреть решение в листинге ниже. Опыт 2 должен показать «расхождений: 0», опыт 4 — 0 байт.

chapters/23-patterns/final/Multimap.cs
public sealed class Multimap<TKey, TValue> where TKey : notnull
{
    readonly Dictionary<TKey, List<TValue>> _map = new();

    public int KeyCount => _map.Count;
    public int Count { get; private set; }

    public void Add(TKey key, TValue value)
    {
        if (!_map.TryGetValue(key, out var list)) _map[key] = list = new();
        list.Add(value);
        Count++;
    }

    public bool Remove(TKey key, TValue value)
    {
        if (!_map.TryGetValue(key, out var list) || !list.Remove(value)) return false;
        Count--;
        if (list.Count == 0) _map.Remove(key);     // пустых списков не копим
        return true;
    }

    public bool ContainsKey(TKey key) => _map.ContainsKey(key);

    // Окно на внутренний список: наружу не уходит ни List<T>, ни возможность его изменить.
    // Окно устаревает при любом Add/Remove по этому ключу (глава 8).
    public ReadOnlySpan<TValue> GetValues(TKey key)
        => _map.TryGetValue(key, out var list) ? CollectionsMarshal.AsSpan(list) : default;
}
  • Строки 12–17: Add создаёт список по требованию.
  • Строки 19–25: Remove удаляет ключ при опустевшем списке — иначе KeyCount и ContainsKey врут, а память копится.
  • Строки 31–32: GetValues отдаёт ReadOnlySpan<TValue> — окно на внутренний список: ни List<T>, ни приведения, ни аллокации; для отсутствующего ключа — пустое окно.
   GetValues(отсутствует): длина 0, выделено 0 Б на 1000 вызовов
   после Remove(b, 3): ключей 1, ContainsKey(b) = False — пустой список не оставлен
   старое окно: длина 2, новое: длина 102 — окно видит старый массив

Предскажите: опыт 4

В chapters/23-patterns/start/Program.cs — строка 162 (метка PREDICT): сколько байт выделит GetValues для отсутствующего ключа? Что станет со старым окном после Add?

Впишите ответ в комментарий до запуска, затем выполните dotnet run -c Release --project 23-patterns\start (вывод опыта начинается с заголовка == Опыт 4.) и сверьтесь с разбором ниже.

Опыт 4 (final).

Окно устаревает при любом Add/Remove по этому ключу (глава 8: рост списка выделяет новый массив, старое окно смотрит на прежний). Для кода, который должен жить дольше одной операции, возвращают копию (ToArray()) или ImmutableArray — это решение границы API (§23.6).

23.5. Вторичные индексы

Основное хранилище — Dictionary<int, Order> по Id; запросы нужны ещё «заказы клиента» и «заказы с суммой в диапазоне». Вторичные индексы — отдельные структуры, которые надо обновлять вместе с основным.

chapters/23-patterns/final/OrderStore.cs
public sealed class OrderStore
{
    readonly Dictionary<int, Order> _byId = new();
    readonly Dictionary<int, List<int>> _byCustomer = new();   // customer → id (а не позиции!)
    (int Amount, int Id)[] _sorted = [];
    bool _dirty;

    public int Count => _byId.Count;

    public void Add(Order o)
    {
        _byId.Add(o.Id, o);
        ref var list = ref CollectionsMarshal.GetValueRefOrAddDefault(_byCustomer, o.Customer, out _);
        (list ??= new()).Add(o.Id);
        _dirty = true;
    }

    public bool Remove(int id)
    {
        if (!_byId.Remove(id, out var o)) return false;
        var list = _byCustomer[o.Customer];
        list.Remove(id);
        if (list.Count == 0) _byCustomer.Remove(o.Customer);
        _dirty = true;
        return true;
    }

    // Правильное обновление: индексы пересчитываются там, где поле — ключ индекса.
    public bool Update(Order n) => Remove(n.Id) && AddReturning(n);

    // Ошибка: основное хранилище обновили, индексы забыли.
    public void UpdateNaive(Order n) => _byId[n.Id] = n;

    bool AddReturning(Order n) { Add(n); return true; }

    public ReadOnlySpan<int> IdsOfCustomer(int customer)
        => _byCustomer.TryGetValue(customer, out var l) ? CollectionsMarshal.AsSpan(l) : default;

    public int CountInRange(int lo, int hi)
    {
        Rebuild();
        int a = LowerBound((lo, int.MinValue));
        int b = LowerBound((hi, int.MaxValue));
        // (hi, MaxValue) может совпасть с реальным элементом; считаем до него включительно
        if (b < _sorted.Length && _sorted[b] == (hi, int.MaxValue)) b++;
        return b - a;
    }

    public int ScanCountInRange(int lo, int hi)
    {
        int n = 0;
        foreach (var o in _byId.Values)
            if (o.Amount >= lo && o.Amount <= hi) n++;
        return n;
    }

    public int ScanCountOfCustomer(int customer)
    {
        int n = 0;
        foreach (var o in _byId.Values)
            if (o.Customer == customer) n++;
        return n;
    }

    public bool Verify(out string problem)
    {
        problem = "";
        foreach (var o in _byId.Values)
        {
            if (!_byCustomer.TryGetValue(o.Customer, out var l) || !l.Contains(o.Id))
            { problem = $"заказ {o.Id}: нет в индексе клиента {o.Customer}"; return false; }
        }
        int ids = 0;
        foreach (var l in _byCustomer.Values) ids += l.Count;
        if (ids != _byId.Count) { problem = $"в индексе клиентов {ids} id, в хранилище {_byId.Count}"; return false; }
        if (!_dirty)   // «грязный» индекс пересоберётся при первом запросе — это не ошибка
        {
            var expected = _byId.Values.Select(o => (o.Amount, o.Id)).Order().ToArray();
            if (!_sorted.AsSpan().SequenceEqual(expected))
            { problem = "индекс по сумме не совпадает с данными"; return false; }
        }
        return true;
    }

    void Rebuild()
    {
        if (!_dirty) return;
        _sorted = _byId.Values.Select(o => (o.Amount, o.Id)).Order().ToArray();
        _dirty = false;
    }

    int LowerBound((int, int) key)
    {
        int lo = 0, hi = _sorted.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (_sorted[mid].CompareTo(key) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
    }
}
  • Строка 7: индекс клиента хранит Id, а не позиции в списке — позиции протухают при любом удалении (в главе 8 RemoveAt сдвигает хвост).
  • Строки 13–29: Add/Remove обновляют все индексы; индекс по сумме — отсортированный массив, помечается _dirty и пересобирается при первом запросе (запись редка, чтение часто).
  • Строка 32: Update = Remove + Add: ключ индекса мог измениться.
  • Строка 35: UpdateNaive — типичная ошибка, меняет только основное хранилище.
  • Строки 68–86: Verify — проверка согласованности (в тестах и при отладке).
   диапазон по сумме: индекс 20030, обход 20030; заказы клиента 17: индекс 92, обход 92
   1000 запросов по клиенту: индекс 0.03 мс, обход 498 мс
   1000 запросов по диапазону: индекс 0.69 мс, обход 848 мс
   после UpdateNaive: Verify = False  «заказ 0: нет в индексе клиента 1999»
   Remove+Add не лечит: Verify = False  «в индексе клиентов 200001 id, в хранилище 200000»
   Update на чистом хранилище: True, Verify = True

Предскажите: опыт 5

В chapters/23-patterns/start/Program.cs — строка 178 (метка PREDICT): во сколько раз индекс быстрее обхода на 200 000 заказов? Заметит ли Verify забытый индекс?

Впишите ответ в комментарий до запуска, затем выполните dotnet run -c Release --project 23-patterns\start (вывод опыта начинается с заголовка == Опыт 5.) и сверьтесь с разбором ниже.

Опыт 5 (final, 200 000 заказов, 2 000 клиентов; «обход» — линейный перебор, замер по 20 запросам и пересчёт на 1000).

  • Выигрыш индекса — 3–4 порядка (0,03–0,07 мс против 300–500 мс на 1000 запросов по клиенту), за счёт линейного обхода, не асимптотики хэша.
  • Забытый индекс не падает: запрос молча отдаёт неверный результат. Хуже: после UpdateNaive заказ остаётся в списке старого клиента, а последующий Remove ищет его уже в списке нового — фантомная запись остаётся навсегда.
  • Следствие для дизайна: единственная точка записи, индексы — приватные, все изменения идут через методы типа; Verify — в тестах.

23.6. Граница API: что отдавать наружу

Тип владеет List<string> _members. Что вернуть вызывающему?

chapters/23-patterns/final/Team.cs
public sealed class Team
{
    readonly List<string> _members = [];
    ImmutableArray<string> _snapshot;
    bool _snapshotValid;

    public void Add(string member)
    {
        _members.Add(member);
        _snapshotValid = false;
    }

    public IEnumerable<string> Leak() => _members;
    public IReadOnlyList<string> View() => _members.AsReadOnly();
    public string[] Copy() => _members.ToArray();

    // Копия делается один раз на серию чтений и сбрасывается при изменении.
    public ImmutableArray<string> Snapshot()
    {
        if (!_snapshotValid)
        {
            _snapshot = ImmutableCollectionsMarshal.AsImmutableArray(_members.ToArray());
            _snapshotValid = true;
        }
        return _snapshot;
    }

    public ReadOnlySpan<string> Window() => CollectionsMarshal.AsSpan(_members);
    public int Count => _members.Count;
   Leak + приведение к List<string>: в команде теперь 3 (добавили снаружи)
   View — это List<string>? False; IList<string>.Add → NotSupportedException
   View живой: после Add в команде view.Count = 4
   обход View + Add внутри: InvalidOperationException
   Snapshot не меняется: 5 элементов, актуально 6

Предскажите: опыт 6

В chapters/23-patterns/start/Program.cs — строка 213 (метка PREDICT): что сможет сделать вызывающий с результатом каждого метода? Сколько байт стоит вызов?

Впишите ответ в комментарий до запуска, затем выполните dotnet run -c Release --project 23-patterns\start (вывод опыта начинается с заголовка == Опыт 6.) и сверьтесь с разбором ниже.

Опыт 6 (final).

Что вернули Приведение к List<T> Видит изменения Цена вызова (N = 10 / 1000)
IEnumerable<T> = сам список (Leak) да, и можно писать да 1,0–1,3 нс, 0 Б
AsReadOnly() (View) нет (NotSupportedException на Add) да (живое окно) 9,5–11 нс, 24 Б
ToArray() (Copy) копия нет 41 нс/104 Б; 1,0 мкс/8 024 Б
кэшированный ImmutableArray (Snapshot) копия, делается раз на серию чтений нет 1,2–1,4 нс, 0 Б (копия — раз после записи)
ReadOnlySpan<T> (Window) — до роста списка 0,4–0,6 нс, 0 Б

Бенчмарки, два прогона.

Правила:

  1. IEnumerable<T>/IReadOnlyList<T> поверх самого списка — не защита: приведение возвращает записываемый List<T>. Это инкапсуляция по соглашению.
  2. AsReadOnly() — защита от записи, но не от изменений: обёртка живая; изменение списка во время обхода — InvalidOperationException у читателя (версия, глава 6). Каждый вызов — новая обёртка (24 Б).
  3. Копия дорога пропорционально размеру: при 1000 элементов — 1 мкс и 8 КБ на каждое чтение. Если читают часто, а пишут редко, кэшируют снимок: копия создаётся при первом чтении после записи (Team.Snapshot, строки 22–30), а ImmutableArray — AsImmutableArray без второй копии (глава 16). Это тот же copy-on-write, что и в главе 18, только без потоков и CAS.
  4. Окно (Span) — самое дешёвое, но только на время вызова: нельзя хранить, нельзя в async, устаревает при росте.
  5. Параметры: принимайте самый узкий интерфейс (IEnumerable<T>, если один проход; IReadOnlyCollection<T>, если нужен Count; ReadOnlySpan<T>, если нужны индекс и скорость) и не перечисляйте дважды (глава 15).

Параллельный доступ

Кэш снимка в Team — не потокобезопасен (флаг и поле пишутся раздельно). Для общих данных публикуют снимок одной ссылкой через Volatile.Write/Interlocked — см. CopyOnWriteList из главы 18.

23.7. Что запомнить

  1. Своя коллекция: ICollection<T> + публичный struct-enumerator + версия. Цена — немного кода; выигрыш — Count() за O(1), ToArray/ToList в 12–20× быстрее и вдвое меньше памяти.
  2. LRU на индексах: словарь ключ → слот и списки на int[] — без аллокаций на промах, ×2,4–2,6 к скорости, в 2 раза меньше памяти; цена — фиксированная ёмкость и сверка с эталоном.
  3. Trie выигрывает только префиксные запросы (≈ 11×) и стоит ≈ 740 Б на слово; для редко меняющихся данных отсортированный массив — на два порядка компактнее.
  4. Multimap: удалять ключ при опустевшем списке, наружу отдавать окно или копию, не List<T>.
  5. Вторичные индексы: хранить Id, а не позиции; одна точка записи; метод проверки согласованности.
  6. Граница API: IEnumerable<T> поверх списка защитой не является; для частых чтений — кэшированный снимок.
  7. Выбор между копией, обёрткой, снимком и окном — это выбор между ценой вызова, актуальностью и безопасностью. Гарантии надо документировать.

23.8. Практикум

Лабораторная: свои коллекции

Задание 1. В chapters/23-patterns/start/Program.cs перед опытами есть строки PREDICT. Впишите предсказания и запустите:

dotnet run -c Release --project 23-patterns\start

Задание 2. Реализуйте IntrusiveLru.MoveToFront в chapters/23-patterns/start/IntrusiveLru.cs и Multimap.GetValues в chapters/23-patterns/start/Multimap.cs. Опыт 2 должен показать «расхождений: 0», опыт 4 — 0 байт.

Задание 3. Замените Dictionary<char, Node> в Trie на отсортированный массив пар (char, Node) с двоичным поиском. Сколько памяти осталось на 100 000 слов и как изменилось время CountWithPrefix?

Задание 4. Сделайте RingCollection<T> быстрее: требуйте ёмкость — степень двойки и замените % на маску. Как изменился Count_EnumerableOnly-подобный обход?

Задание 5. Добавьте в OrderStore индекс по Customer как SortedSet и сравните с Dictionary<int, List<int>> на запросах диапазона клиентов. Что даёт сортированный индекс, чего нет у хэш-индекса?

Задание 6. Напишите Team.SnapshotThreadSafe() на Volatile.Read/Interlocked.Exchange и тест на гонку (спин-барьер из главы 20).

Ответы

1. Чаще всего ошибаются: «IEnumerable<T> защищает от записи» (нет), «в foreach struct-enumerator быстрее интерфейсного» (на горячем бенчмарке — одинаково), «trie быстрее HashSet на точный поиск» (в 7–10 раз медленнее), «индекс в памяти бесплатен» (он должен обновляться всегда).

2. MoveToFront: if (_head == i) return; Unlink(i); PushFront(i);. GetValues: CollectionsMarshal.AsSpan(list) для найденного ключа, default — иначе.

3. Ожидание: узел с 1–3 потомками хранит пары в маленьком массиве вместо Dictionary — память падает в разы; CountWithPrefix меняется мало (в узлах мало потомков). Проверьте замером — в тексте главы не измерялось.

4. Для ёмкости 2ⁿ: (head + i) & (cap − 1). Ёмкость — поле, а не константа, поэтому JIT сам % на маску не заменит; проверьте в asm, что idiv исчез.

5. Упорядоченный обход и выборка по диапазону (GetViewBetween, но Count у вида O(k) — глава 11); у хэш-индекса диапазона нет.

6. Снимок пересоздаётся под lock или публикуется новый ImmutableArray через Interlocked.Exchange; читатели берут ссылку один раз.

Код лабораторной

using System.Diagnostics;

Console.WriteLine($"Стенд: {Environment.OSVersion}, ядер {Environment.ProcessorCount}, рантайм {Environment.Version}\n");

static long Bytes(Action a)
{
    a();
    long before = GC.GetAllocatedBytesForCurrentThread();
    a();
    return GC.GetAllocatedBytesForCurrentThread() - before;
}

static long Heap()
{
    GC.Collect(2, GCCollectionMode.Forced, true, true);
    return GC.GetTotalMemory(true);
}

static double Ms(Action a, int reps = 3)
{
    a();
    Thread.Sleep(150);
    a();
    double best = double.MaxValue;
    for (int r = 0; r < reps; r++)
    {
        var sw = Stopwatch.StartNew();
        a();
        best = Math.Min(best, sw.Elapsed.TotalMilliseconds);
    }
    return best;
}

static void Run(string title, Action body)
{
    Console.WriteLine(title);
    try { body(); }
    catch (NotImplementedException e) { Console.WriteLine($"   {e.Message}"); }
    Console.WriteLine();
}

// ---------------------------------------------------------------------------------------------
Run("== Опыт 1. Свой кольцевой буфер: что даёт ICollection<T> ==", () =>
{
    // PREDICT: во сколько раз различаются байты ToArray()/ToList() у буфера только с IEnumerable<T>
    // и у буфера с ICollection<T>? Что делает Count()?
    const int N = 1000;
    var only = new RingEnumerable<int>(N);
    var full = new RingCollection<int>(N);
    for (int i = 0; i < N + 300; i++) { only.Add(i); full.Add(i); }

    Console.WriteLine($"   содержимое совпадает: {only.SequenceEqual(full)}");
    Console.WriteLine($"   только IEnumerable: ToArray {Bytes(() => only.ToArray()),6} Б, ToList {Bytes(() => only.ToList()),6} Б, Count() {Bytes(() => only.Count()),4} Б");
    Console.WriteLine($"   ICollection<T>:     ToArray {Bytes(() => full.ToArray()),6} Б, ToList {Bytes(() => full.ToList()),6} Б, Count() {Bytes(() => full.Count()),4} Б");
    Console.WriteLine($"   TryGetNonEnumeratedCount: только IEnumerable = {only.TryGetNonEnumeratedCount(out _)}, ICollection<T> = {full.TryGetNonEnumeratedCount(out int c)} ({c})");

    int sum = 0;
    foreach (var x in full) sum += x;
    IEnumerable<int> asIface = full;
    int sum2 = 0;
    foreach (var x in asIface) sum2 += x;
    Console.WriteLine($"   foreach по struct-enumerator'у: {Bytes(() => { foreach (var x in full) sum += x; })} Б; через IEnumerable<T>: {Bytes(() => { foreach (var x in asIface) sum2 += x; })} Б (sum совпали: {sum == sum2})");

    var arr = new int[N + 5];
    full.CopyTo(arr, 5);
    Console.WriteLine($"   CopyTo(arr, 5): arr[5] = {arr[5]}, arr[{N + 4}] = {arr[N + 4]} (ожидаем 300 и {N + 299})");
    try { foreach (var x in full) full.Add(x); }
    catch (InvalidOperationException e) { Console.WriteLine($"   изменение при обходе: {e.GetType().Name}"); }
    try { ((ICollection<int>)full).Remove(1); }
    catch (NotSupportedException) { Console.WriteLine("   Remove: NotSupportedException (контракт это допускает)"); }
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 2. LRU: узлы на индексах против LinkedList ==", () =>
{
    // PREDICT: порядок вытеснения совпадёт у обеих реализаций? Сколько байт на запись и на промах?
    var a = new IntrusiveLru<int, int>(8);
    var b = new ClassicLru<int, int>(8);
    var rnd = new Random(7);
    int diffs = 0, hitsA = 0, hitsB = 0;
    for (int i = 0; i < 20_000; i++)
    {
        int k = rnd.Next(0, 24);
        if (rnd.Next(3) == 0) { a.Set(k, i); b.Set(k, i); }
        else
        {
            bool ha = a.TryGet(k, out int va), hb = b.TryGet(k, out int vb);
            if (ha) hitsA++;
            if (hb) hitsB++;
            if (ha != hb || va != vb) diffs++;
        }
        if (i % 500 == 0 && !a.KeysMostRecentFirst().SequenceEqual(b.KeysMostRecentFirst())) diffs++;
    }
    Console.WriteLine($"   расхождений порядка/значений: {diffs}, попаданий {hitsA} и {hitsB}");

    const int Cap = 100_000;
    long h0 = Heap();
    var big1 = new IntrusiveLru<int, int>(Cap);
    for (int i = 0; i < Cap; i++) big1.Set(i, i);
    long h1 = Heap();
    var big2 = new ClassicLru<int, int>(Cap);
    for (int i = 0; i < Cap; i++) big2.Set(i, i);
    long h2 = Heap();
    Console.WriteLine($"   память на запись при {Cap:N0}: на индексах {(h1 - h0) / (double)Cap:F1} Б, Dictionary+LinkedList {(h2 - h1) / (double)Cap:F1} Б");
    GC.KeepAlive(big1); GC.KeepAlive(big2);

    var c1 = new IntrusiveLru<int, int>(1024);
    var c2 = new ClassicLru<int, int>(1024);
    Console.WriteLine($"   промахи (10 000 Set новых ключей): на индексах {Bytes(() => { for (int i = 0; i < 10_000; i++) c1.Set(i + 5000, i); })} Б, LinkedList {Bytes(() => { for (int i = 0; i < 10_000; i++) c2.Set(i + 5000, i); })} Б");
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 3. Trie или отсортированный массив: префиксные запросы ==", () =>
{
    // PREDICT: что компактнее и что быстрее на 100 000 слов — trie или массив + двоичный поиск?
    var rnd = new Random(11);
    var words = new HashSet<string>();
    while (words.Count < 100_000)
    {
        int len = rnd.Next(3, 11);
        words.Add(string.Create(len, rnd.Next(), (span, seed) =>
        {
            var r = new Random(seed);
            for (int i = 0; i < span.Length; i++) span[i] = (char)('a' + r.Next(26));
        }));
    }
    var list = words.ToList();

    long h0 = Heap();
    var sorted = new SortedWords(list);
    long h1 = Heap();
    var trie = new Trie();
    foreach (var w in list) trie.Add(w);
    long h2 = Heap();
    var hs = new HashSet<string>(list);
    long h3 = Heap();
    Console.WriteLine($"   слов {sorted.Count:N0}/{trie.Count:N0}. Память поверх самих строк: массив {(h1 - h0) / 1024} КБ, trie {(h2 - h1) / 1024} КБ, HashSet {(h3 - h2) / 1024} КБ");

    int bad = 0;
    var prefixes = list.Take(2000).Select(w => w[..rnd.Next(1, Math.Min(4, w.Length) + 1)]).ToArray();
    foreach (var p in prefixes)
    {
        int expected = list.Count(w => w.StartsWith(p, StringComparison.Ordinal));
        if (trie.CountWithPrefix(p) != expected || sorted.CountWithPrefix(p) != expected) bad++;
        if (trie.WithPrefix(p).Count() != expected) bad++;
    }
    Console.WriteLine($"   расхождений CountWithPrefix/WithPrefix на {prefixes.Length} префиксах: {bad}");

    int x = 0;
    double mTrie = Ms(() => { foreach (var p in prefixes) x += trie.CountWithPrefix(p); });
    double mSorted = Ms(() => { foreach (var p in prefixes) x += sorted.CountWithPrefix(p); });
    double mContainsT = Ms(() => { foreach (var w in list) if (trie.Contains(w)) x++; });
    double mContainsH = Ms(() => { foreach (var w in list) if (hs.Contains(w)) x++; });
    Console.WriteLine($"   CountWithPrefix × {prefixes.Length}: trie {mTrie * 1000:F0} мкс, массив {mSorted * 1000:F0} мкс");
    Console.WriteLine($"   Contains × {list.Count:N0}: trie {mContainsT:F1} мс, HashSet {mContainsH:F1} мс");
    GC.KeepAlive(x);
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 4. Multimap ==", () =>
{
    // PREDICT: сколько байт выделит GetValues для отсутствующего ключа? Что станет со старым окном после Add?
    var mm = new Multimap<string, int>();
    mm.Add("a", 1); mm.Add("a", 2); mm.Add("b", 3);
    Console.WriteLine($"   пар {mm.Count}, ключей {mm.KeyCount}; a → [{string.Join(", ", mm.GetValues("a").ToArray())}]");
    Console.WriteLine($"   GetValues(отсутствует): длина {mm.GetValues("zzz").Length}, выделено {Bytes(() => { for (int i = 0; i < 1000; i++) _ = mm.GetValues("zzz").Length; })} Б на 1000 вызовов");
    mm.Remove("b", 3);
    Console.WriteLine($"   после Remove(b, 3): ключей {mm.KeyCount}, ContainsKey(b) = {mm.ContainsKey("b")} — пустой список не оставлен");

    var window = mm.GetValues("a");
    for (int i = 0; i < 100; i++) mm.Add("a", 100 + i);
    Console.WriteLine($"   старое окно: длина {window.Length}, новое: длина {mm.GetValues("a").Length} — окно видит старый массив");
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 5. Вторичные индексы ==", () =>
{
    // PREDICT: во сколько раз индекс быстрее обхода на 200 000 заказов? Заметит ли Verify забытый индекс?
    var rnd = new Random(5);
    var store = new OrderStore();
    for (int id = 0; id < 200_000; id++) store.Add(new Order(id, rnd.Next(2000), rnd.Next(10_000)));

    int a = store.CountInRange(1000, 1999), b = store.ScanCountInRange(1000, 1999);
    int c = store.IdsOfCustomer(17).Length, d = store.ScanCountOfCustomer(17);
    Console.WriteLine($"   диапазон по сумме: индекс {a}, обход {b}; заказы клиента 17: индекс {c}, обход {d}");

    int x = 0;
    double mIdx = Ms(() => { for (int i = 0; i < 1000; i++) x += store.IdsOfCustomer(i % 2000).Length; });
    double mScan = Ms(() => { for (int i = 0; i < 20; i++) x += store.ScanCountOfCustomer(i % 2000); }) / 20 * 1000;
    double mRangeIdx = Ms(() => { for (int i = 0; i < 1000; i++) x += store.CountInRange(i, i + 500); });
    double mRangeScan = Ms(() => { for (int i = 0; i < 20; i++) x += store.ScanCountInRange(i, i + 500); }) / 20 * 1000;
    Console.WriteLine($"   1000 запросов по клиенту: индекс {mIdx:F2} мс, обход {mScan:F0} мс");
    Console.WriteLine($"   1000 запросов по диапазону: индекс {mRangeIdx:F2} мс, обход {mRangeScan:F0} мс");

    Console.WriteLine($"   Verify до правок: {store.Verify(out var p0)} {p0}");
    store.UpdateNaive(new Order(0, 1999, 1));
    Console.WriteLine($"   после UpdateNaive: Verify = {store.Verify(out var p1)}  «{p1}»");
    store.Remove(0);
    store.Add(new Order(0, 1999, 1));
    store.Remove(0);
    store.Add(new Order(0, 1999, 1));
    Console.WriteLine($"   Remove+Add не лечит: Verify = {store.Verify(out var p2)}  «{p2}» (запись в старом списке клиента осталась)");

    var fresh = new OrderStore();
    for (int id = 0; id < 100; id++) fresh.Add(new Order(id, id % 7, id * 3));
    Console.WriteLine($"   Update на чистом хранилище: {fresh.Update(new Order(1, 3, 3))}, Verify = {fresh.Verify(out var p3)} {p3}");
    GC.KeepAlive(x);
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 6. Граница API ==", () =>
{
    // PREDICT: что сможет сделать вызывающий с результатом каждого метода? Сколько байт стоит вызов?
    var team = new Team();
    team.Add("ann"); team.Add("bob");

    var leaked = team.Leak();
    ((List<string>)leaked).Add("mallory");
    Console.WriteLine($"   Leak + приведение к List<string>: в команде теперь {team.Count} (добавили снаружи)");

    var view = team.View();
    Console.WriteLine($"   View — это List<string>? {view is List<string>}; IList<string>.Add → {Try(() => ((IList<string>)view).Add("eve"))}");
    team.Add("carol");
    Console.WriteLine($"   View живой: после Add в команде view.Count = {view.Count}");
    try { foreach (var _ in view) team.Add("dave"); }
    catch (InvalidOperationException) { Console.WriteLine("   обход View + Add внутри: InvalidOperationException"); }

    var snap = team.Snapshot();
    team.Add("erin");
    Console.WriteLine($"   Snapshot не меняется: {snap.Length} элементов, актуально {team.Snapshot().Length}");

    Console.WriteLine($"   байт на 1000 вызовов: Leak {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Leak(); })}, View {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.View(); })}, Copy {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Copy(); })}, Snapshot {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Snapshot(); })}, Window {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Window().Length; })}");
});

static string Try(Action a)
{
    try { a(); return "прошло"; }
    catch (Exception e) { return e.GetType().Name; }
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Классический LRU: Dictionary + LinkedList (узел на каждую вставку)
public sealed class ClassicLru<TKey, TValue>(int capacity) where TKey : notnull
{
    readonly Dictionary<TKey, LinkedListNode<(TKey Key, TValue Value)>> _map = new(capacity);
    readonly LinkedList<(TKey Key, TValue Value)> _list = new();

    public int Count => _map.Count;

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _list.Remove(node);
            _list.AddFirst(node);
            value = node.Value.Value;
            return true;
        }
        value = default!;
        return false;
    }

    public void Set(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _list.Remove(node);
            _list.AddFirst(node);
            node.Value = (key, value);
            return;
        }
        if (_map.Count >= capacity)
        {
            _map.Remove(_list.Last!.Value.Key);
            _list.RemoveLast();
        }
        _map[key] = _list.AddFirst((key, value));
    }

    public IEnumerable<TKey> KeysMostRecentFirst() => _list.Select(p => p.Key);
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// LRU: Dictionary + двусвязный список на индексах массивов
public sealed class IntrusiveLru<TKey, TValue> where TKey : notnull
{
    readonly Dictionary<TKey, int> _map;
    readonly TKey[] _keys;
    readonly TValue[] _values;
    readonly int[] _prev, _next;
    int _head = -1, _tail = -1, _count;

    public IntrusiveLru(int capacity)
    {
        _map = new(capacity);
        _keys = new TKey[capacity];
        _values = new TValue[capacity];
        _prev = new int[capacity];
        _next = new int[capacity];
    }

    public int Count => _count;

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out int i))
        {
            MoveToFront(i);
            value = _values[i];
            return true;
        }
        value = default!;
        return false;
    }

    public void Set(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out int i))
        {
            _values[i] = value;
            MoveToFront(i);
            return;
        }
        if (_count < _keys.Length) i = _count++;
        else
        {
            i = _tail;                 // вытесняем самого давнего, его слот переиспользуем
            _map.Remove(_keys[i]);
            Unlink(i);
        }
        _keys[i] = key;
        _values[i] = value;
        _map[key] = i;
        PushFront(i);
    }

    public IEnumerable<TKey> KeysMostRecentFirst()
    {
        for (int i = _head; i >= 0; i = _next[i]) yield return _keys[i];
    }

    void Unlink(int i)
    {
        int p = _prev[i], n = _next[i];
        if (p >= 0) _next[p] = n; else _head = n;
        if (n >= 0) _prev[n] = p; else _tail = p;
    }

    void PushFront(int i)
    {
        _prev[i] = -1;
        _next[i] = _head;
        if (_head >= 0) _prev[_head] = i;
        _head = i;
        if (_tail < 0) _tail = i;
    }

    void MoveToFront(int i)
    {
        // TODO 1: вынуть узел i из списка и поставить в голову.
        // Подсказка: Unlink, затем PushFront; если узел уже голова — ничего не делать.
        throw new NotImplementedException("TODO 1: IntrusiveLru.MoveToFront");
    }
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Multimap
public sealed class Multimap<TKey, TValue> where TKey : notnull
{
    readonly Dictionary<TKey, List<TValue>> _map = new();

    public int KeyCount => _map.Count;
    public int Count { get; private set; }

    public void Add(TKey key, TValue value)
    {
        if (!_map.TryGetValue(key, out var list)) _map[key] = list = new();
        list.Add(value);
        Count++;
    }

    public bool Remove(TKey key, TValue value)
    {
        if (!_map.TryGetValue(key, out var list) || !list.Remove(value)) return false;
        Count--;
        if (list.Count == 0) _map.Remove(key);     // пустых списков не копим
        return true;
    }

    public bool ContainsKey(TKey key) => _map.ContainsKey(key);

    // Окно на внутренний список: наружу не уходит ни List<T>, ни возможность его изменить.
    // Окно устаревает при любом Add/Remove по этому ключу (глава 8).
    public ReadOnlySpan<TValue> GetValues(TKey key)
    {
        // TODO 2: вернуть окно на список без аллокаций; для отсутствующего ключа — пустое окно.
        // Подсказка: CollectionsMarshal.AsSpan(list).
        throw new NotImplementedException("TODO 2: Multimap.GetValues");
    }
}
1
2
3
4
5
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Хранилище с вторичными индексами
public readonly record struct Order(int Id, int Customer, int Amount);
using System.Collections.Immutable;
using System.Runtime.InteropServices;

public sealed class OrderStore
{
    readonly Dictionary<int, Order> _byId = new();
    readonly Dictionary<int, List<int>> _byCustomer = new();   // customer → id (а не позиции!)
    (int Amount, int Id)[] _sorted = [];
    bool _dirty;

    public int Count => _byId.Count;

    public void Add(Order o)
    {
        _byId.Add(o.Id, o);
        ref var list = ref CollectionsMarshal.GetValueRefOrAddDefault(_byCustomer, o.Customer, out _);
        (list ??= new()).Add(o.Id);
        _dirty = true;
    }

    public bool Remove(int id)
    {
        if (!_byId.Remove(id, out var o)) return false;
        var list = _byCustomer[o.Customer];
        list.Remove(id);
        if (list.Count == 0) _byCustomer.Remove(o.Customer);
        _dirty = true;
        return true;
    }

    // Правильное обновление: индексы пересчитываются там, где поле — ключ индекса.
    public bool Update(Order n) => Remove(n.Id) && AddReturning(n);

    // Ошибка: основное хранилище обновили, индексы забыли.
    public void UpdateNaive(Order n) => _byId[n.Id] = n;

    bool AddReturning(Order n) { Add(n); return true; }

    public ReadOnlySpan<int> IdsOfCustomer(int customer)
        => _byCustomer.TryGetValue(customer, out var l) ? CollectionsMarshal.AsSpan(l) : default;

    public int CountInRange(int lo, int hi)
    {
        Rebuild();
        int a = LowerBound((lo, int.MinValue));
        int b = LowerBound((hi, int.MaxValue));
        // (hi, MaxValue) может совпасть с реальным элементом; считаем до него включительно
        if (b < _sorted.Length && _sorted[b] == (hi, int.MaxValue)) b++;
        return b - a;
    }

    public int ScanCountInRange(int lo, int hi)
    {
        int n = 0;
        foreach (var o in _byId.Values)
            if (o.Amount >= lo && o.Amount <= hi) n++;
        return n;
    }

    public int ScanCountOfCustomer(int customer)
    {
        int n = 0;
        foreach (var o in _byId.Values)
            if (o.Customer == customer) n++;
        return n;
    }

    public bool Verify(out string problem)
    {
        problem = "";
        foreach (var o in _byId.Values)
        {
            if (!_byCustomer.TryGetValue(o.Customer, out var l) || !l.Contains(o.Id))
            { problem = $"заказ {o.Id}: нет в индексе клиента {o.Customer}"; return false; }
        }
        int ids = 0;
        foreach (var l in _byCustomer.Values) ids += l.Count;
        if (ids != _byId.Count) { problem = $"в индексе клиентов {ids} id, в хранилище {_byId.Count}"; return false; }
        if (!_dirty)   // «грязный» индекс пересоберётся при первом запросе — это не ошибка
        {
            var expected = _byId.Values.Select(o => (o.Amount, o.Id)).Order().ToArray();
            if (!_sorted.AsSpan().SequenceEqual(expected))
            { problem = "индекс по сумме не совпадает с данными"; return false; }
        }
        return true;
    }

    void Rebuild()
    {
        if (!_dirty) return;
        _sorted = _byId.Values.Select(o => (o.Amount, o.Id)).Order().ToArray();
        _dirty = false;
    }

    int LowerBound((int, int) key)
    {
        int lo = 0, hi = _sorted.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (_sorted[mid].CompareTo(key) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
    }
}
using System.Collections;
using System.Runtime.InteropServices;

// Тот же буфер «по правилам»: ICollection<T> + IReadOnlyList<T> + struct-enumerator
public sealed class RingCollection<T>(int capacity) : ICollection<T>, IReadOnlyList<T>
{
    readonly T[] _items = new T[capacity];
    int _head, _count, _version;

    public int Count => _count;
    bool ICollection<T>.IsReadOnly => false;

    public T this[int index]
    {
        get
        {
            if ((uint)index >= (uint)_count) throw new ArgumentOutOfRangeException(nameof(index));
            return _items[(_head + index) % _items.Length];
        }
    }

    public void Add(T item)
    {
        if (_count < _items.Length) _items[(_head + _count++) % _items.Length] = item;
        else { _items[_head] = item; _head = (_head + 1) % _items.Length; }
        _version++;
    }

    public void Clear()
    {
        Array.Clear(_items);
        _head = _count = 0;
        _version++;
    }

    public bool Contains(T item)
    {
        var cmp = EqualityComparer<T>.Default;
        for (int i = 0; i < _count; i++)
            if (cmp.Equals(_items[(_head + i) % _items.Length], item)) return true;
        return false;
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        ArgumentNullException.ThrowIfNull(array);
        ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
        if (array.Length - arrayIndex < _count) throw new ArgumentException("Массив мал.", nameof(array));
        int first = Math.Min(_count, _items.Length - _head);
        Array.Copy(_items, _head, array, arrayIndex, first);
        Array.Copy(_items, 0, array, arrayIndex + first, _count - first);
    }

    // Удаление из середины кольца не поддерживаем — контракт ICollection<T> допускает NotSupportedException.
    bool ICollection<T>.Remove(T item) => throw new NotSupportedException();

    public Enumerator GetEnumerator() => new(this);
    IEnumerator<T> IEnumerable<T>.GetEnumerator() => new Enumerator(this);
    IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);

    public struct Enumerator : IEnumerator<T>
    {
        readonly RingCollection<T> _ring;
        readonly int _version;
        int _index;
        T _current;

        internal Enumerator(RingCollection<T> ring)
        {
            _ring = ring;
            _version = ring._version;
            _index = 0;
            _current = default!;
        }

        public T Current => _current;
        object? IEnumerator.Current => _current;

        public bool MoveNext()
        {
            if (_version != _ring._version) throw new InvalidOperationException("Коллекция изменена во время перечисления.");
            if (_index >= _ring._count) return false;
            _current = _ring[_index++];
            return true;
        }

        public void Reset() { _index = 0; _current = default!; }
        public void Dispose() { }
    }
}
using System.Collections;
using System.Runtime.InteropServices;

// Кольцевой буфер: только IEnumerable<T>
public sealed class RingEnumerable<T>(int capacity) : IEnumerable<T>
{
    readonly T[] _items = new T[capacity];
    int _head, _count;

    public void Add(T item)
    {
        if (_count < _items.Length) _items[(_head + _count++) % _items.Length] = item;
        else { _items[_head] = item; _head = (_head + 1) % _items.Length; }
    }

    public IEnumerator<T> GetEnumerator()
    {
        for (int i = 0; i < _count; i++) yield return _items[(_head + i) % _items.Length];
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

public sealed class SortedWords
{
    readonly string[] _words;

    public SortedWords(IEnumerable<string> words)
    {
        _words = words.Distinct().ToArray();
        Array.Sort(_words, StringComparer.Ordinal);
    }

    public int Count => _words.Length;

    public bool Contains(string word) => Array.BinarySearch(_words, word, StringComparer.Ordinal) >= 0;

    // Две двоичные границы: первый элемент >= prefix и первый после блока с этим префиксом.
    public int CountWithPrefix(string prefix)
    {
        int lo = 0, hi = _words.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (string.CompareOrdinal(_words[mid], prefix) < 0) lo = mid + 1; else hi = mid;
        }
        int first = lo;
        hi = _words.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (_words[mid].StartsWith(prefix, StringComparison.Ordinal)) lo = mid + 1; else hi = mid;
        }
        return lo - first;
    }
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Граница API
public sealed class Team
{
    readonly List<string> _members = [];
    ImmutableArray<string> _snapshot;
    bool _snapshotValid;

    public void Add(string member)
    {
        _members.Add(member);
        _snapshotValid = false;
    }

    public IEnumerable<string> Leak() => _members;
    public IReadOnlyList<string> View() => _members.AsReadOnly();
    public string[] Copy() => _members.ToArray();

    // Копия делается один раз на серию чтений и сбрасывается при изменении.
    public ImmutableArray<string> Snapshot()
    {
        if (!_snapshotValid)
        {
            _snapshot = ImmutableCollectionsMarshal.AsImmutableArray(_members.ToArray());
            _snapshotValid = true;
        }
        return _snapshot;
    }

    public ReadOnlySpan<string> Window() => CollectionsMarshal.AsSpan(_members);
    public int Count => _members.Count;
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Trie со счётчиком проходов и отсортированный массив
public sealed class Trie
{
    sealed class Node
    {
        public Dictionary<char, Node>? Next;
        public int Pass;      // сколько слов проходит через узел (включая закончившиеся в нём)
        public bool End;
    }

    readonly Node _root = new();
    public int Count => _root.Pass;

    public bool Add(string word)
    {
        if (Contains(word)) return false;
        var node = _root;
        node.Pass++;
        foreach (char c in word)
        {
            node.Next ??= new();
            if (!node.Next.TryGetValue(c, out var child)) node.Next[c] = child = new();
            node = child;
            node.Pass++;
        }
        node.End = true;
        return true;
    }

    public bool Contains(string word) => Find(word) is { End: true };

    public int CountWithPrefix(string prefix) => Find(prefix)?.Pass ?? 0;

    public IEnumerable<string> WithPrefix(string prefix)
    {
        var node = Find(prefix);
        if (node is null) yield break;
        var stack = new Stack<(Node Node, string Text)>();
        stack.Push((node, prefix));
        while (stack.Count > 0)
        {
            var (n, text) = stack.Pop();
            if (n.End) yield return text;
            if (n.Next is null) continue;
            foreach (var (c, child) in n.Next) stack.Push((child, text + c));
        }
    }

    Node? Find(ReadOnlySpan<char> s)
    {
        var node = _root;
        foreach (char c in s)
            if (node.Next is null || !node.Next.TryGetValue(c, out node)) return null;
        return node;
    }
}
using System.Diagnostics;

Console.WriteLine($"Стенд: {Environment.OSVersion}, ядер {Environment.ProcessorCount}, рантайм {Environment.Version}\n");

static long Bytes(Action a)
{
    a();
    long before = GC.GetAllocatedBytesForCurrentThread();
    a();
    return GC.GetAllocatedBytesForCurrentThread() - before;
}

static long Heap()
{
    GC.Collect(2, GCCollectionMode.Forced, true, true);
    return GC.GetTotalMemory(true);
}

static double Ms(Action a, int reps = 3)
{
    a();
    Thread.Sleep(150);
    a();
    double best = double.MaxValue;
    for (int r = 0; r < reps; r++)
    {
        var sw = Stopwatch.StartNew();
        a();
        best = Math.Min(best, sw.Elapsed.TotalMilliseconds);
    }
    return best;
}

static void Run(string title, Action body)
{
    Console.WriteLine(title);
    try { body(); }
    catch (NotImplementedException e) { Console.WriteLine($"   {e.Message}"); }
    Console.WriteLine();
}

// ---------------------------------------------------------------------------------------------
Run("== Опыт 1. Свой кольцевой буфер: что даёт ICollection<T> ==", () =>
{
    // PREDICT: во сколько раз различаются байты ToArray()/ToList() у буфера только с IEnumerable<T>
    // и у буфера с ICollection<T>? Что делает Count()?
    const int N = 1000;
    var only = new RingEnumerable<int>(N);
    var full = new RingCollection<int>(N);
    for (int i = 0; i < N + 300; i++) { only.Add(i); full.Add(i); }

    Console.WriteLine($"   содержимое совпадает: {only.SequenceEqual(full)}");
    Console.WriteLine($"   только IEnumerable: ToArray {Bytes(() => only.ToArray()),6} Б, ToList {Bytes(() => only.ToList()),6} Б, Count() {Bytes(() => only.Count()),4} Б");
    Console.WriteLine($"   ICollection<T>:     ToArray {Bytes(() => full.ToArray()),6} Б, ToList {Bytes(() => full.ToList()),6} Б, Count() {Bytes(() => full.Count()),4} Б");
    Console.WriteLine($"   TryGetNonEnumeratedCount: только IEnumerable = {only.TryGetNonEnumeratedCount(out _)}, ICollection<T> = {full.TryGetNonEnumeratedCount(out int c)} ({c})");

    int sum = 0;
    foreach (var x in full) sum += x;
    IEnumerable<int> asIface = full;
    int sum2 = 0;
    foreach (var x in asIface) sum2 += x;
    Console.WriteLine($"   foreach по struct-enumerator'у: {Bytes(() => { foreach (var x in full) sum += x; })} Б; через IEnumerable<T>: {Bytes(() => { foreach (var x in asIface) sum2 += x; })} Б (sum совпали: {sum == sum2})");

    var arr = new int[N + 5];
    full.CopyTo(arr, 5);
    Console.WriteLine($"   CopyTo(arr, 5): arr[5] = {arr[5]}, arr[{N + 4}] = {arr[N + 4]} (ожидаем 300 и {N + 299})");
    try { foreach (var x in full) full.Add(x); }
    catch (InvalidOperationException e) { Console.WriteLine($"   изменение при обходе: {e.GetType().Name}"); }
    try { ((ICollection<int>)full).Remove(1); }
    catch (NotSupportedException) { Console.WriteLine("   Remove: NotSupportedException (контракт это допускает)"); }
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 2. LRU: узлы на индексах против LinkedList ==", () =>
{
    // PREDICT: порядок вытеснения совпадёт у обеих реализаций? Сколько байт на запись и на промах?
    var a = new IntrusiveLru<int, int>(8);
    var b = new ClassicLru<int, int>(8);
    var rnd = new Random(7);
    int diffs = 0, hitsA = 0, hitsB = 0;
    for (int i = 0; i < 20_000; i++)
    {
        int k = rnd.Next(0, 24);
        if (rnd.Next(3) == 0) { a.Set(k, i); b.Set(k, i); }
        else
        {
            bool ha = a.TryGet(k, out int va), hb = b.TryGet(k, out int vb);
            if (ha) hitsA++;
            if (hb) hitsB++;
            if (ha != hb || va != vb) diffs++;
        }
        if (i % 500 == 0 && !a.KeysMostRecentFirst().SequenceEqual(b.KeysMostRecentFirst())) diffs++;
    }
    Console.WriteLine($"   расхождений порядка/значений: {diffs}, попаданий {hitsA} и {hitsB}");

    const int Cap = 100_000;
    long h0 = Heap();
    var big1 = new IntrusiveLru<int, int>(Cap);
    for (int i = 0; i < Cap; i++) big1.Set(i, i);
    long h1 = Heap();
    var big2 = new ClassicLru<int, int>(Cap);
    for (int i = 0; i < Cap; i++) big2.Set(i, i);
    long h2 = Heap();
    Console.WriteLine($"   память на запись при {Cap:N0}: на индексах {(h1 - h0) / (double)Cap:F1} Б, Dictionary+LinkedList {(h2 - h1) / (double)Cap:F1} Б");
    GC.KeepAlive(big1); GC.KeepAlive(big2);

    var c1 = new IntrusiveLru<int, int>(1024);
    var c2 = new ClassicLru<int, int>(1024);
    Console.WriteLine($"   промахи (10 000 Set новых ключей): на индексах {Bytes(() => { for (int i = 0; i < 10_000; i++) c1.Set(i + 5000, i); })} Б, LinkedList {Bytes(() => { for (int i = 0; i < 10_000; i++) c2.Set(i + 5000, i); })} Б");
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 3. Trie или отсортированный массив: префиксные запросы ==", () =>
{
    // PREDICT: что компактнее и что быстрее на 100 000 слов — trie или массив + двоичный поиск?
    var rnd = new Random(11);
    var words = new HashSet<string>();
    while (words.Count < 100_000)
    {
        int len = rnd.Next(3, 11);
        words.Add(string.Create(len, rnd.Next(), (span, seed) =>
        {
            var r = new Random(seed);
            for (int i = 0; i < span.Length; i++) span[i] = (char)('a' + r.Next(26));
        }));
    }
    var list = words.ToList();

    long h0 = Heap();
    var sorted = new SortedWords(list);
    long h1 = Heap();
    var trie = new Trie();
    foreach (var w in list) trie.Add(w);
    long h2 = Heap();
    var hs = new HashSet<string>(list);
    long h3 = Heap();
    Console.WriteLine($"   слов {sorted.Count:N0}/{trie.Count:N0}. Память поверх самих строк: массив {(h1 - h0) / 1024} КБ, trie {(h2 - h1) / 1024} КБ, HashSet {(h3 - h2) / 1024} КБ");

    int bad = 0;
    var prefixes = list.Take(2000).Select(w => w[..rnd.Next(1, Math.Min(4, w.Length) + 1)]).ToArray();
    foreach (var p in prefixes)
    {
        int expected = list.Count(w => w.StartsWith(p, StringComparison.Ordinal));
        if (trie.CountWithPrefix(p) != expected || sorted.CountWithPrefix(p) != expected) bad++;
        if (trie.WithPrefix(p).Count() != expected) bad++;
    }
    Console.WriteLine($"   расхождений CountWithPrefix/WithPrefix на {prefixes.Length} префиксах: {bad}");

    int x = 0;
    double mTrie = Ms(() => { foreach (var p in prefixes) x += trie.CountWithPrefix(p); });
    double mSorted = Ms(() => { foreach (var p in prefixes) x += sorted.CountWithPrefix(p); });
    double mContainsT = Ms(() => { foreach (var w in list) if (trie.Contains(w)) x++; });
    double mContainsH = Ms(() => { foreach (var w in list) if (hs.Contains(w)) x++; });
    Console.WriteLine($"   CountWithPrefix × {prefixes.Length}: trie {mTrie * 1000:F0} мкс, массив {mSorted * 1000:F0} мкс");
    Console.WriteLine($"   Contains × {list.Count:N0}: trie {mContainsT:F1} мс, HashSet {mContainsH:F1} мс");
    GC.KeepAlive(x);
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 4. Multimap ==", () =>
{
    // PREDICT: сколько байт выделит GetValues для отсутствующего ключа? Что станет со старым окном после Add?
    var mm = new Multimap<string, int>();
    mm.Add("a", 1); mm.Add("a", 2); mm.Add("b", 3);
    Console.WriteLine($"   пар {mm.Count}, ключей {mm.KeyCount}; a → [{string.Join(", ", mm.GetValues("a").ToArray())}]");
    Console.WriteLine($"   GetValues(отсутствует): длина {mm.GetValues("zzz").Length}, выделено {Bytes(() => { for (int i = 0; i < 1000; i++) _ = mm.GetValues("zzz").Length; })} Б на 1000 вызовов");
    mm.Remove("b", 3);
    Console.WriteLine($"   после Remove(b, 3): ключей {mm.KeyCount}, ContainsKey(b) = {mm.ContainsKey("b")} — пустой список не оставлен");

    var window = mm.GetValues("a");
    for (int i = 0; i < 100; i++) mm.Add("a", 100 + i);
    Console.WriteLine($"   старое окно: длина {window.Length}, новое: длина {mm.GetValues("a").Length} — окно видит старый массив");
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 5. Вторичные индексы ==", () =>
{
    // PREDICT: во сколько раз индекс быстрее обхода на 200 000 заказов? Заметит ли Verify забытый индекс?
    var rnd = new Random(5);
    var store = new OrderStore();
    for (int id = 0; id < 200_000; id++) store.Add(new Order(id, rnd.Next(2000), rnd.Next(10_000)));

    int a = store.CountInRange(1000, 1999), b = store.ScanCountInRange(1000, 1999);
    int c = store.IdsOfCustomer(17).Length, d = store.ScanCountOfCustomer(17);
    Console.WriteLine($"   диапазон по сумме: индекс {a}, обход {b}; заказы клиента 17: индекс {c}, обход {d}");

    int x = 0;
    double mIdx = Ms(() => { for (int i = 0; i < 1000; i++) x += store.IdsOfCustomer(i % 2000).Length; });
    double mScan = Ms(() => { for (int i = 0; i < 20; i++) x += store.ScanCountOfCustomer(i % 2000); }) / 20 * 1000;
    double mRangeIdx = Ms(() => { for (int i = 0; i < 1000; i++) x += store.CountInRange(i, i + 500); });
    double mRangeScan = Ms(() => { for (int i = 0; i < 20; i++) x += store.ScanCountInRange(i, i + 500); }) / 20 * 1000;
    Console.WriteLine($"   1000 запросов по клиенту: индекс {mIdx:F2} мс, обход {mScan:F0} мс");
    Console.WriteLine($"   1000 запросов по диапазону: индекс {mRangeIdx:F2} мс, обход {mRangeScan:F0} мс");

    Console.WriteLine($"   Verify до правок: {store.Verify(out var p0)} {p0}");
    store.UpdateNaive(new Order(0, 1999, 1));
    Console.WriteLine($"   после UpdateNaive: Verify = {store.Verify(out var p1)}  «{p1}»");
    store.Remove(0);
    store.Add(new Order(0, 1999, 1));
    store.Remove(0);
    store.Add(new Order(0, 1999, 1));
    Console.WriteLine($"   Remove+Add не лечит: Verify = {store.Verify(out var p2)}  «{p2}» (запись в старом списке клиента осталась)");

    var fresh = new OrderStore();
    for (int id = 0; id < 100; id++) fresh.Add(new Order(id, id % 7, id * 3));
    Console.WriteLine($"   Update на чистом хранилище: {fresh.Update(new Order(1, 3, 3))}, Verify = {fresh.Verify(out var p3)} {p3}");
    GC.KeepAlive(x);
});

// ---------------------------------------------------------------------------------------------
Run("== Опыт 6. Граница API ==", () =>
{
    // PREDICT: что сможет сделать вызывающий с результатом каждого метода? Сколько байт стоит вызов?
    var team = new Team();
    team.Add("ann"); team.Add("bob");

    var leaked = team.Leak();
    ((List<string>)leaked).Add("mallory");
    Console.WriteLine($"   Leak + приведение к List<string>: в команде теперь {team.Count} (добавили снаружи)");

    var view = team.View();
    Console.WriteLine($"   View — это List<string>? {view is List<string>}; IList<string>.Add → {Try(() => ((IList<string>)view).Add("eve"))}");
    team.Add("carol");
    Console.WriteLine($"   View живой: после Add в команде view.Count = {view.Count}");
    try { foreach (var _ in view) team.Add("dave"); }
    catch (InvalidOperationException) { Console.WriteLine("   обход View + Add внутри: InvalidOperationException"); }

    var snap = team.Snapshot();
    team.Add("erin");
    Console.WriteLine($"   Snapshot не меняется: {snap.Length} элементов, актуально {team.Snapshot().Length}");

    Console.WriteLine($"   байт на 1000 вызовов: Leak {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Leak(); })}, View {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.View(); })}, Copy {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Copy(); })}, Snapshot {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Snapshot(); })}, Window {Bytes(() => { for (int i = 0; i < 1000; i++) _ = team.Window().Length; })}");
});

static string Try(Action a)
{
    try { a(); return "прошло"; }
    catch (Exception e) { return e.GetType().Name; }
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Классический LRU: Dictionary + LinkedList (узел на каждую вставку)
public sealed class ClassicLru<TKey, TValue>(int capacity) where TKey : notnull
{
    readonly Dictionary<TKey, LinkedListNode<(TKey Key, TValue Value)>> _map = new(capacity);
    readonly LinkedList<(TKey Key, TValue Value)> _list = new();

    public int Count => _map.Count;

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _list.Remove(node);
            _list.AddFirst(node);
            value = node.Value.Value;
            return true;
        }
        value = default!;
        return false;
    }

    public void Set(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _list.Remove(node);
            _list.AddFirst(node);
            node.Value = (key, value);
            return;
        }
        if (_map.Count >= capacity)
        {
            _map.Remove(_list.Last!.Value.Key);
            _list.RemoveLast();
        }
        _map[key] = _list.AddFirst((key, value));
    }

    public IEnumerable<TKey> KeysMostRecentFirst() => _list.Select(p => p.Key);
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// LRU: Dictionary + двусвязный список на индексах массивов
public sealed class IntrusiveLru<TKey, TValue> where TKey : notnull
{
    readonly Dictionary<TKey, int> _map;
    readonly TKey[] _keys;
    readonly TValue[] _values;
    readonly int[] _prev, _next;
    int _head = -1, _tail = -1, _count;

    public IntrusiveLru(int capacity)
    {
        _map = new(capacity);
        _keys = new TKey[capacity];
        _values = new TValue[capacity];
        _prev = new int[capacity];
        _next = new int[capacity];
    }

    public int Count => _count;

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out int i))
        {
            MoveToFront(i);
            value = _values[i];
            return true;
        }
        value = default!;
        return false;
    }

    public void Set(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out int i))
        {
            _values[i] = value;
            MoveToFront(i);
            return;
        }
        if (_count < _keys.Length) i = _count++;
        else
        {
            i = _tail;                 // вытесняем самого давнего, его слот переиспользуем
            _map.Remove(_keys[i]);
            Unlink(i);
        }
        _keys[i] = key;
        _values[i] = value;
        _map[key] = i;
        PushFront(i);
    }

    public IEnumerable<TKey> KeysMostRecentFirst()
    {
        for (int i = _head; i >= 0; i = _next[i]) yield return _keys[i];
    }

    void Unlink(int i)
    {
        int p = _prev[i], n = _next[i];
        if (p >= 0) _next[p] = n; else _head = n;
        if (n >= 0) _prev[n] = p; else _tail = p;
    }

    void PushFront(int i)
    {
        _prev[i] = -1;
        _next[i] = _head;
        if (_head >= 0) _prev[_head] = i;
        _head = i;
        if (_tail < 0) _tail = i;
    }

    void MoveToFront(int i)
    {
        if (_head == i) return;
        Unlink(i);
        PushFront(i);
    }
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Multimap
public sealed class Multimap<TKey, TValue> where TKey : notnull
{
    readonly Dictionary<TKey, List<TValue>> _map = new();

    public int KeyCount => _map.Count;
    public int Count { get; private set; }

    public void Add(TKey key, TValue value)
    {
        if (!_map.TryGetValue(key, out var list)) _map[key] = list = new();
        list.Add(value);
        Count++;
    }

    public bool Remove(TKey key, TValue value)
    {
        if (!_map.TryGetValue(key, out var list) || !list.Remove(value)) return false;
        Count--;
        if (list.Count == 0) _map.Remove(key);     // пустых списков не копим
        return true;
    }

    public bool ContainsKey(TKey key) => _map.ContainsKey(key);

    // Окно на внутренний список: наружу не уходит ни List<T>, ни возможность его изменить.
    // Окно устаревает при любом Add/Remove по этому ключу (глава 8).
    public ReadOnlySpan<TValue> GetValues(TKey key)
        => _map.TryGetValue(key, out var list) ? CollectionsMarshal.AsSpan(list) : default;
}
1
2
3
4
5
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Хранилище с вторичными индексами
public readonly record struct Order(int Id, int Customer, int Amount);
using System.Collections.Immutable;
using System.Runtime.InteropServices;

public sealed class OrderStore
{
    readonly Dictionary<int, Order> _byId = new();
    readonly Dictionary<int, List<int>> _byCustomer = new();   // customer → id (а не позиции!)
    (int Amount, int Id)[] _sorted = [];
    bool _dirty;

    public int Count => _byId.Count;

    public void Add(Order o)
    {
        _byId.Add(o.Id, o);
        ref var list = ref CollectionsMarshal.GetValueRefOrAddDefault(_byCustomer, o.Customer, out _);
        (list ??= new()).Add(o.Id);
        _dirty = true;
    }

    public bool Remove(int id)
    {
        if (!_byId.Remove(id, out var o)) return false;
        var list = _byCustomer[o.Customer];
        list.Remove(id);
        if (list.Count == 0) _byCustomer.Remove(o.Customer);
        _dirty = true;
        return true;
    }

    // Правильное обновление: индексы пересчитываются там, где поле — ключ индекса.
    public bool Update(Order n) => Remove(n.Id) && AddReturning(n);

    // Ошибка: основное хранилище обновили, индексы забыли.
    public void UpdateNaive(Order n) => _byId[n.Id] = n;

    bool AddReturning(Order n) { Add(n); return true; }

    public ReadOnlySpan<int> IdsOfCustomer(int customer)
        => _byCustomer.TryGetValue(customer, out var l) ? CollectionsMarshal.AsSpan(l) : default;

    public int CountInRange(int lo, int hi)
    {
        Rebuild();
        int a = LowerBound((lo, int.MinValue));
        int b = LowerBound((hi, int.MaxValue));
        // (hi, MaxValue) может совпасть с реальным элементом; считаем до него включительно
        if (b < _sorted.Length && _sorted[b] == (hi, int.MaxValue)) b++;
        return b - a;
    }

    public int ScanCountInRange(int lo, int hi)
    {
        int n = 0;
        foreach (var o in _byId.Values)
            if (o.Amount >= lo && o.Amount <= hi) n++;
        return n;
    }

    public int ScanCountOfCustomer(int customer)
    {
        int n = 0;
        foreach (var o in _byId.Values)
            if (o.Customer == customer) n++;
        return n;
    }

    public bool Verify(out string problem)
    {
        problem = "";
        foreach (var o in _byId.Values)
        {
            if (!_byCustomer.TryGetValue(o.Customer, out var l) || !l.Contains(o.Id))
            { problem = $"заказ {o.Id}: нет в индексе клиента {o.Customer}"; return false; }
        }
        int ids = 0;
        foreach (var l in _byCustomer.Values) ids += l.Count;
        if (ids != _byId.Count) { problem = $"в индексе клиентов {ids} id, в хранилище {_byId.Count}"; return false; }
        if (!_dirty)   // «грязный» индекс пересоберётся при первом запросе — это не ошибка
        {
            var expected = _byId.Values.Select(o => (o.Amount, o.Id)).Order().ToArray();
            if (!_sorted.AsSpan().SequenceEqual(expected))
            { problem = "индекс по сумме не совпадает с данными"; return false; }
        }
        return true;
    }

    void Rebuild()
    {
        if (!_dirty) return;
        _sorted = _byId.Values.Select(o => (o.Amount, o.Id)).Order().ToArray();
        _dirty = false;
    }

    int LowerBound((int, int) key)
    {
        int lo = 0, hi = _sorted.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (_sorted[mid].CompareTo(key) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
    }
}
using System.Collections;
using System.Runtime.InteropServices;

// Тот же буфер «по правилам»: ICollection<T> + IReadOnlyList<T> + struct-enumerator
public sealed class RingCollection<T>(int capacity) : ICollection<T>, IReadOnlyList<T>
{
    readonly T[] _items = new T[capacity];
    int _head, _count, _version;

    public int Count => _count;
    bool ICollection<T>.IsReadOnly => false;

    public T this[int index]
    {
        get
        {
            if ((uint)index >= (uint)_count) throw new ArgumentOutOfRangeException(nameof(index));
            return _items[(_head + index) % _items.Length];
        }
    }

    public void Add(T item)
    {
        if (_count < _items.Length) _items[(_head + _count++) % _items.Length] = item;
        else { _items[_head] = item; _head = (_head + 1) % _items.Length; }
        _version++;
    }

    public void Clear()
    {
        Array.Clear(_items);
        _head = _count = 0;
        _version++;
    }

    public bool Contains(T item)
    {
        var cmp = EqualityComparer<T>.Default;
        for (int i = 0; i < _count; i++)
            if (cmp.Equals(_items[(_head + i) % _items.Length], item)) return true;
        return false;
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        ArgumentNullException.ThrowIfNull(array);
        ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
        if (array.Length - arrayIndex < _count) throw new ArgumentException("Массив мал.", nameof(array));
        int first = Math.Min(_count, _items.Length - _head);
        Array.Copy(_items, _head, array, arrayIndex, first);
        Array.Copy(_items, 0, array, arrayIndex + first, _count - first);
    }

    // Удаление из середины кольца не поддерживаем — контракт ICollection<T> допускает NotSupportedException.
    bool ICollection<T>.Remove(T item) => throw new NotSupportedException();

    public Enumerator GetEnumerator() => new(this);
    IEnumerator<T> IEnumerable<T>.GetEnumerator() => new Enumerator(this);
    IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this);

    public struct Enumerator : IEnumerator<T>
    {
        readonly RingCollection<T> _ring;
        readonly int _version;
        int _index;
        T _current;

        internal Enumerator(RingCollection<T> ring)
        {
            _ring = ring;
            _version = ring._version;
            _index = 0;
            _current = default!;
        }

        public T Current => _current;
        object? IEnumerator.Current => _current;

        public bool MoveNext()
        {
            if (_version != _ring._version) throw new InvalidOperationException("Коллекция изменена во время перечисления.");
            if (_index >= _ring._count) return false;
            _current = _ring[_index++];
            return true;
        }

        public void Reset() { _index = 0; _current = default!; }
        public void Dispose() { }
    }
}
using System.Collections;
using System.Runtime.InteropServices;

// Кольцевой буфер: только IEnumerable<T>
public sealed class RingEnumerable<T>(int capacity) : IEnumerable<T>
{
    readonly T[] _items = new T[capacity];
    int _head, _count;

    public void Add(T item)
    {
        if (_count < _items.Length) _items[(_head + _count++) % _items.Length] = item;
        else { _items[_head] = item; _head = (_head + 1) % _items.Length; }
    }

    public IEnumerator<T> GetEnumerator()
    {
        for (int i = 0; i < _count; i++) yield return _items[(_head + i) % _items.Length];
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

public sealed class SortedWords
{
    readonly string[] _words;

    public SortedWords(IEnumerable<string> words)
    {
        _words = words.Distinct().ToArray();
        Array.Sort(_words, StringComparer.Ordinal);
    }

    public int Count => _words.Length;

    public bool Contains(string word) => Array.BinarySearch(_words, word, StringComparer.Ordinal) >= 0;

    // Две двоичные границы: первый элемент >= prefix и первый после блока с этим префиксом.
    public int CountWithPrefix(string prefix)
    {
        int lo = 0, hi = _words.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (string.CompareOrdinal(_words[mid], prefix) < 0) lo = mid + 1; else hi = mid;
        }
        int first = lo;
        hi = _words.Length;
        while (lo < hi)
        {
            int mid = (lo + hi) >>> 1;
            if (_words[mid].StartsWith(prefix, StringComparison.Ordinal)) lo = mid + 1; else hi = mid;
        }
        return lo - first;
    }
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Граница API
public sealed class Team
{
    readonly List<string> _members = [];
    ImmutableArray<string> _snapshot;
    bool _snapshotValid;

    public void Add(string member)
    {
        _members.Add(member);
        _snapshotValid = false;
    }

    public IEnumerable<string> Leak() => _members;
    public IReadOnlyList<string> View() => _members.AsReadOnly();
    public string[] Copy() => _members.ToArray();

    // Копия делается один раз на серию чтений и сбрасывается при изменении.
    public ImmutableArray<string> Snapshot()
    {
        if (!_snapshotValid)
        {
            _snapshot = ImmutableCollectionsMarshal.AsImmutableArray(_members.ToArray());
            _snapshotValid = true;
        }
        return _snapshot;
    }

    public ReadOnlySpan<string> Window() => CollectionsMarshal.AsSpan(_members);
    public int Count => _members.Count;
}
using System.Collections.Immutable;
using System.Runtime.InteropServices;

// Trie со счётчиком проходов и отсортированный массив
public sealed class Trie
{
    sealed class Node
    {
        public Dictionary<char, Node>? Next;
        public int Pass;      // сколько слов проходит через узел (включая закончившиеся в нём)
        public bool End;
    }

    readonly Node _root = new();
    public int Count => _root.Pass;

    public bool Add(string word)
    {
        if (Contains(word)) return false;
        var node = _root;
        node.Pass++;
        foreach (char c in word)
        {
            node.Next ??= new();
            if (!node.Next.TryGetValue(c, out var child)) node.Next[c] = child = new();
            node = child;
            node.Pass++;
        }
        node.End = true;
        return true;
    }

    public bool Contains(string word) => Find(word) is { End: true };

    public int CountWithPrefix(string prefix) => Find(prefix)?.Pass ?? 0;

    public IEnumerable<string> WithPrefix(string prefix)
    {
        var node = Find(prefix);
        if (node is null) yield break;
        var stack = new Stack<(Node Node, string Text)>();
        stack.Push((node, prefix));
        while (stack.Count > 0)
        {
            var (n, text) = stack.Pop();
            if (n.End) yield return text;
            if (n.Next is null) continue;
            foreach (var (c, child) in n.Next) stack.Push((child, text + c));
        }
    }

    Node? Find(ReadOnlySpan<char> s)
    {
        var node = _root;
        foreach (char c in s)
            if (node.Next is null || !node.Next.TryGetValue(c, out node)) return null;
        return node;
    }
}
1
2
3
4
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkSwitcher.FromAssembly(typeof(RingBench).Assembly).Run(args);
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

// Выдача внутреннего состояния: цена одного вызова
[MemoryDiagnoser]
public class BoundaryBench
{
    [Params(10, 1000)]
    public int N;

    Team _team = null!;

    [GlobalSetup]
    public void Setup()
    {
        _team = new Team();
        for (int i = 0; i < N; i++) _team.Add("m" + i);
    }

    [Benchmark(Baseline = true)] public object Leak() => _team.Leak();
    [Benchmark] public object View() => _team.View();
    [Benchmark] public object Copy() => _team.Copy();
    [Benchmark] public int Snapshot() => _team.Snapshot().Length;
    [Benchmark] public int Window() => _team.Window().Length;
}
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

// LRU: 80 % попаданий, 20 % вставок новых ключей
[MemoryDiagnoser]
public class LruBench
{
    const int Cap = 1024, Ops = 10_000;
    int[] _keys = null!;
    IntrusiveLru<int, int> _a = null!;
    ClassicLru<int, int> _b = null!;
    ReuseLru<int, int> _c = null!;

    [GlobalSetup]
    public void Setup()
    {
        var rnd = new Random(1);
        _keys = new int[Ops];
        for (int i = 0; i < Ops; i++)
            _keys[i] = rnd.Next(10) < 8 ? rnd.Next(Cap / 2) : Cap + rnd.Next(1_000_000);
        _a = new(Cap);
        _b = new(Cap);
        _c = new(Cap);
        for (int i = 0; i < Cap; i++) { _a.Set(i, i); _b.Set(i, i); _c.Set(i, i); }
    }

    [Benchmark(Baseline = true)]
    public int Classic()
    {
        int hits = 0;
        foreach (int k in _keys)
        {
            if (_b.TryGet(k, out _)) hits++;
            else _b.Set(k, k);
        }
        return hits;
    }

    [Benchmark]
    public int ClassicReuse()
    {
        int hits = 0;
        foreach (int k in _keys)
        {
            if (_c.TryGet(k, out _)) hits++;
            else _c.Set(k, k);
        }
        return hits;
    }

    [Benchmark]
    public int Intrusive()
    {
        int hits = 0;
        foreach (int k in _keys)
        {
            if (_a.TryGet(k, out _)) hits++;
            else _a.Set(k, k);
        }
        return hits;
    }
}
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

// Классический LRU, но вытесняемый узел переиспользуется (без new LinkedListNode на промах)
public sealed class ReuseLru<TKey, TValue>(int capacity) where TKey : notnull
{
    readonly Dictionary<TKey, LinkedListNode<(TKey Key, TValue Value)>> _map = new(capacity);
    readonly LinkedList<(TKey Key, TValue Value)> _list = new();

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _list.Remove(node);
            _list.AddFirst(node);
            value = node.Value.Value;
            return true;
        }
        value = default!;
        return false;
    }

    public void Set(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _list.Remove(node);
            node.Value = (key, value);
            _list.AddFirst(node);
            return;
        }
        if (_map.Count >= capacity)
        {
            var last = _list.Last!;
            _map.Remove(last.Value.Key);
            _list.RemoveLast();
            last.Value = (key, value);
            _list.AddFirst(last);
            _map[key] = last;
        }
        else _map[key] = _list.AddFirst((key, value));
    }
}
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

// Что даёт ICollection<T>: ToList/ToArray/Count через CopyTo и Count
[MemoryDiagnoser]
public class RingBench
{
    [Params(10, 1000)]
    public int N;

    RingEnumerable<int> _only = null!;
    RingCollection<int> _full = null!;

    [GlobalSetup]
    public void Setup()
    {
        _only = new RingEnumerable<int>(N);
        _full = new RingCollection<int>(N);
        for (int i = 0; i < N; i++) { _only.Add(i); _full.Add(i); }
    }

    [Benchmark(Baseline = true)] public List<int> ToList_EnumerableOnly() => _only.ToList();
    [Benchmark] public List<int> ToList_Collection() => _full.ToList();
    [Benchmark] public int[] ToArray_EnumerableOnly() => _only.ToArray();
    [Benchmark] public int[] ToArray_Collection() => _full.ToArray();
    [Benchmark] public int Count_EnumerableOnly() => _only.Count();
    [Benchmark] public int Count_Collection() => _full.Count();

    [Benchmark]
    public int Foreach_Struct()
    {
        int s = 0;
        foreach (var x in _full) s += x;
        return s;
    }

    [Benchmark]
    public int Foreach_Interface()
    {
        int s = 0;
        foreach (var x in (IEnumerable<int>)_full) s += x;
        return s;
    }
}
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

// Префиксный подсчёт и Contains: trie против массива и HashSet
[MemoryDiagnoser]
public class TrieBench
{
    Trie _trie = null!;
    SortedWords _sorted = null!;
    HashSet<string> _set = null!;
    string[] _prefixes = null!;
    string[] _words = null!;

    [GlobalSetup]
    public void Setup()
    {
        var rnd = new Random(11);
        var words = new HashSet<string>();
        var buf = new char[10];
        while (words.Count < 100_000)
        {
            int len = rnd.Next(3, 11);
            for (int i = 0; i < len; i++) buf[i] = (char)('a' + rnd.Next(26));
            words.Add(new string(buf, 0, len));
        }
        _words = words.ToArray();
        _trie = new Trie();
        foreach (var w in _words) _trie.Add(w);
        _sorted = new SortedWords(_words);
        _set = new HashSet<string>(_words);
        _prefixes = _words.Take(1000).Select(w => w[..Math.Min(3, w.Length)]).ToArray();
    }

    [Benchmark]
    public int PrefixCount_Trie()
    {
        int s = 0;
        foreach (var p in _prefixes) s += _trie.CountWithPrefix(p);
        return s;
    }

    [Benchmark(Baseline = true)]
    public int PrefixCount_SortedArray()
    {
        int s = 0;
        foreach (var p in _prefixes) s += _sorted.CountWithPrefix(p);
        return s;
    }

    [Benchmark]
    public int Contains_Trie()
    {
        int s = 0;
        for (int i = 0; i < 1000; i++) if (_trie.Contains(_words[i])) s++;
        return s;
    }

    [Benchmark]
    public int Contains_HashSet()
    {
        int s = 0;
        for (int i = 0; i < 1000; i++) if (_set.Contains(_words[i])) s++;
        return s;
    }
}