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

13. Выражения коллекций

О главе

Цель: выяснить, что на самом деле делает [a, b, ..c]. У выражения коллекции нет «своего» типа — компилятор выбирает код по целевому типу, и стоимость различается на порядки: от нуля байт (константы в ReadOnlySpan<int> лежат в образе сборки) до промежуточного List<T> и двух копий (spread по ленивой последовательности). Разбираем IL для каждого целевого типа, <>z__ReadOnlyArray<T> под IEnumerable<T>, InlineArrayN на стеке, params ReadOnlySpan<T>, CollectionBuilderAttribute и выбор перегрузки.

Опирается на: главу 3 — span, stackalloc, [InlineArray], статические данные. Главу 8 — CollectionsMarshal.SetCount/AsSpan, ёмкость. Главу 10 — HashSet/Dictionary и их ёмкость.

Лабораторная: 13-collection-expressions/start — шесть опытов с предсказаниями (PREDICT) и TODO: Bag.Create для CollectionBuilder; final — результат; bench — четыре группы бенчмарков.

Стенд: Ubuntu 26.04, 2 ядра AMD EPYC Rome (виртуальная машина), рантайм 10.0.12, SDK 10.0.401 (Roslyn для C# 14). IL снят tools\disasm.ps1 -Mode il,cs -Type Samples.

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

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

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

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

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

start/ final/
Назначение то, что вы предсказываете и правите эталон и дополнительные опыты
Файлы с TODO Bag2.cs реализации
Одинаковые файлы Bag.cs, Measure.cs, Overloads.cs, Samples.cs менять не нужно

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

13.1. Целевой тип решает всё

Выражение коллекции — список элементов в [ ]; ..x вставляет все элементы последовательности x (spread). Своего типа у [1, 2, 3] нет: оно преобразуется в то, чего ждёт контекст. Допустимые целевые типы:

  • массив (int[]);
  • Span<T> и ReadOnlySpan<T>;
  • тип с атрибутом [CollectionBuilder] (§13.6);
  • тип с доступным конструктором без параметров и Add, реализующий IEnumerable (то есть всё, что допускает collection initializer: List<T>, HashSet<T>, Queue<T>…);
  • интерфейсы IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>.

Что именно сгенерирует компилятор для каждого, видно только в IL. Метод на каждый целевой тип, [MethodImpl(NoInlining)], декомпиляция -Mode il,cs:

chapters/13-collection-expressions/final/Samples.cs
    // --- массив ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadArray(int[] src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadList(List<int> src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadEnumerable(IEnumerable<int> src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayEmpty() => [];

    // --- List<T> ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListSpreadArray(int[] src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListSpreadEnumerable(IEnumerable<int> src) => [.. src, 4];

    // --- span ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static ReadOnlySpan<int> SpanConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int SpanVarSum(int a, int b)
    {
        ReadOnlySpan<int> s = [a, b, 3];     // не выходит из метода: место можно взять на стеке
        int sum = 0;
        foreach (var x in s) sum += x;
        return sum;
    }

13.2. Во что превращается [...]

Результат разбора IL (SDK 10.0.401; один и тот же для трёх элементов-констант и трёх переменных, где это не оговорено):

Целевой тип Что делает код Куда пишет
int[], константы newarr + RuntimeHelpers.InitializeArray(array, ldtoken <данные>) копия данных из образа сборки
int[], переменные newarr + stelem на каждый элемент куча
int[], [] Array.Empty<int>() общий пустой массив, без аллокации
List<int> new List<int>(n) → CollectionsMarshal.SetCount(list, n) → AsSpan → запись по индексу куча; ёмкость ровно n
ReadOnlySpan<int>, константы RuntimeHelpers.CreateSpan<int>(ldtoken <данные>) статические данные образа, без копии
ReadOnlySpan<int>, переменные локальная InlineArray3<int> + InlineArrayAsReadOnlySpan стек
Span<int> то же: локальная InlineArrayN, но не статические данные (изменяемый) стек
IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T> new <>z__ReadOnlyArray<T>(new T[] { … }) куча: массив + обёртка
ICollection<T>, IList<T> как для List<T> куча
HashSet<T>, Queue<T>… new T() и Add на каждый элемент (collection initializer) без подсказки ёмкости
ImmutableArray<T> new T[] { … } + ImmutableCollectionsMarshal.AsImmutableArray массив отдаётся без копирования
свой тип с [CollectionBuilder] Create(ReadOnlySpan<T>) аргумент — статические данные или InlineArrayN

Три замечания к таблице.

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

В chapters/13-collection-expressions/start/Program.cs — строка 8 (метка PREDICT): какой тип у IEnumerable x = [1, 2, 3]? Можно ли привести его к List? К IList?

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

<>z__ReadOnlyArray<T> — тип, который компилятор генерирует в вашей сборке. Он оборачивает массив и реализует IList<T>, IReadOnlyList<T>, ICollection<T> и необобщённые IList/ICollection, но все изменяющие операции бросают NotSupportedException (опыт 1):

   IEnumerable<int> x = [1,2,3]: is List<int> = False, is int[] = False, is IList<int> = True
   запись по индексу: NotSupportedException
   Add: NotSupportedException
   интерфейсы <>z__ReadOnlyArray`1: IEnumerable, ICollection, IList, IEnumerable`1, IReadOnlyCollection`1, IReadOnlyList`1, ICollection`1, IList`1

То есть IEnumerable<int> x = [1, 2, 3] — не List<int>, не int[], но is IList<int> истинно, IsReadOnly = True. Это та же ловушка «IsReadOnly у IList<T>», что у массива в главе 5; код, который проверяет is IList<T> и затем пишет, получит исключение.

InlineArray2 … InlineArray16 — публичные типы BCL, появились в .NET 10 (опыт на стенде: все 15 типов с именами InlineArray21…InlineArray161 в System.Runtime.CompilerServices, у каждого [InlineArray(N)]). Для 17 и более элементов компилятор создаёт собственный <>y__InlineArrayN в вашей сборке: проверено на 17 и 100 элементах.

Queue<int> q = [1, 2, 3] — не то же, что new Queue<int>([1, 2, 3]). Во втором случае конструктор принимает IEnumerable<int>, и выражение превращается в <>z__ReadOnlyArray (массив + обёртка, 64 байта): конструктору Queue нужен IEnumerable, а не Add.

13.3. Сколько байт

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

В chapters/13-collection-expressions/start/Program.cs — строка 48 (метка PREDICT): что из этого не выделит ни байта?

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

Опыт 2: каждый метод вызывается 150 раз с паузами (чтобы JIT успел поставить Tier1) и затем измеряется один вызов; три элемента (int):

Выражение Байт
int[] = [1, 2, 3] 40
int[] = [a, b, 3] 40
int[] = [] 0
List<int> = [1, 2, 3] 72 (список 32 + массив 40)
new List<int> { 1, 2, 3 } 72
ReadOnlySpan<int> = [1, 2, 3] 0
ReadOnlySpan<int> = [a, b, 3] 0
Span<int> = [a, b, 3] 0
IEnumerable<int> = [1, 2, 3] 64 (массив 40 + обёртка 24)
IEnumerable<int> = [] 0
HashSet<int> = [1, 2, 2, 3] 168 (без подсказки ёмкости: три роста)
ImmutableArray<int> = [a, b, 3] 40
Bag<int> = [1, 2, 3] (свой builder) 64 (Bag 24 + копия массива 40)

Ловушка: до прогрева константный массив стоит на 72 байта больше

Опыт 2 печатает ещё одну строку, которую легко принять за ошибку:

   (до прогрева, Tier0: int[] = [1,2,3] — 112 Б, IEnumerable<int> = [1,2,3] — 136 Б)

Константный массив в Tier0 выделяет 112 байт вместо 40, обёртка над ним — 136 вместо 64. После перехода метода на Tier1 лишние 72 байта исчезают (в отдельной проверке: три раунда по 1000 вызовов с паузами 250 мс — 112 → 112 → 112 → 40). Причина — неразвёрнутый RuntimeHelpers.InitializeArray: в неоптимизированном коде он не раскрывается как intrinsic, и fldHandle.GetRuntimeFieldInfo() выделяет объект RuntimeFieldInfoStub — ровно 72 байта (заголовок и MethodTable 16, пять ссылок 40, int с выравниванием 8, RuntimeFieldHandleInternal 8; декомпиляция CoreLib 10.0.12). Это и есть разница 112 − 40. Для замеров аллокаций прогревайте метод: это то же правило, что в главе 0.

Главное в таблице:

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

В chapters/13-collection-expressions/start/Program.cs — строка 85 (метка PREDICT): одинаковы ли адреса данных у двух вызовов SpanConst()? А у двух вызовов ArrayConst()?

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

  • […] в ReadOnlySpan<T> не выделяет ничего — ни с константами (данные уже в образе), ни с переменными (буфер на стеке).
  • List<int> = [...] не быстрее new List<int> { … } по памяти (те же 72 байта), но быстрее по времени (§13.7): точная ёмкость вместо роста и запись Span вместо Add.
  • HashSet из выражения не получает ёмкости: выражение — это collection initializer. Для больших множеств создавайте с ёмкостью и добавляйте сами.

13.4. Spread

..x — «вставить все элементы». Для измерения нужно число элементов, чтобы выделить результат один раз. Что делает компилятор, зависит от типа x (опыт 2):

Источник Результат Как Байт (int[4] + 1 элемент)
int[] int[] new int[1 + src.Length]; ReadOnlySpan.CopyTo 48
List<int> int[] new int[1 + src.Count]; CollectionsMarshal.AsSpan(list).CopyTo 48
int[] List<int> List(n) + SetCount + CopyTo в AsSpan 80
IEnumerable<int> (под ним массив) int[] new List<int>() → AddRange → Add → ToArray 176
IEnumerable<int> (ленивый Where) int[] то же 224
IEnumerable<int> (ленивый) List<int> new List<int>() + AddRange + Add 176
декомпиляция: ArraySpreadEnumerable(IEnumerable<int> src) => [.. src, 4]
List<int> list = new List<int>();
list.AddRange(src);
list.Add(4);
return list.ToArray();

Для int[] и List<int> компилятор знает длину сразу и копирует блоком. Для IEnumerable<int> он не может знать длину без прохода: собирает промежуточный List<int> (рост — те же 4 → 8 → …) и делает ещё одну копию в ToArray. Если src — на самом деле массив или ICollection<T>, AddRange берёт размер из Count, но промежуточный список и вторая копия всё равно есть: решение принято по статическому типу.

Склейка двух массивов (SpreadBench, N — длина каждого, два прогона):

Способ N = 100 N = 10 000 Выделено при N = 100
[.. a, .. b] 67–72 нс 5,2–6,0 мкс 824 Б
new int[] + два Array.Copy вручную 67–72 нс 5,1–5,7 мкс 824 Б
a.Concat(b).ToArray() 97–103 нс (1,4×) 5,2–7,1 мкс 880 Б
List.AddRange ×2 + ToArray 219–235 нс (3,3×) 13,2–14,3 мкс (2,4–2,6×) 2104 Б
[.. a.Where(...), .. b] 817–968 нс (11–14×) 98–107 мкс (18–19×) 3104 Б

Выражение [.. a, .. b] совпадает с ручным кодом по времени и памяти — абстракция бесплатна. Дорого другое: spread по IEnumerable — в 11–19 раз медленнее, потому что идёт перебор через интерфейс, рост списка и вторая копия.

13.5. params с коллекциями (C# 13)

Начиная с C# 13 params принимает не только массив, но и Span<T>, ReadOnlySpan<T>, IEnumerable<T> и другие типы коллекций. Три объявления одного метода — вызов Sum(a, b, 3) (опыт 2):

Объявление Что строит вызывающий Байт
params int[] new int[3] 40
params ReadOnlySpan<int> InlineArray3<int> на стеке 0
params IEnumerable<int> <>z__ReadOnlyArray + массив, а foreach добавляет энумератор 96

В бенчмарке картина мягче (ParamsBench, три значения, два прогона): params int[] — 2,0 нс и 0 байт; params ReadOnlySpan<int> — 1,6–1,7 нс; params IEnumerable<int> — 9,4–9,8 нс и 40 байт. Нулевая аллокация у params int[] — результат escape analysis (глава 7): в бенчмарке Sum — маленький приватный метод, его встраивают, и массив не выходит из метода — .NET 10 кладёт его на стек. В лабораторной Sum* помечены NoInlining, поэтому 40 байт. Не рассчитывайте на escape analysis для params int[] в публичном API: гарантированно ноль только у ReadOnlySpan.

Для константных аргументов (Sum(1, 2, 3)) ReadOnlySpan быстрее ещё и по времени (1,2–1,3 нс против 2,3–2,4): данные уже готовы в образе, массив не заполняется.

Выбор перегрузки

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

В chapters/13-collection-expressions/start/Program.cs — строка 100 (метка PREDICT): какую перегрузку выберет компилятор?

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

Опыт 4:

   A(int[]) / A(ReadOnlySpan<int>)        <- [1,2,3]: ReadOnlySpan<int>
   B(List<int>) / B(IEnumerable<int>)     <- [1,2,3]: List<int>
   C(int[]) / C(List<int>) — вызов не компилируется (CS0121: неоднозначно)

Правило: из двух применимых целевых типов лучше тот, к которому преобразование «специфичнее» — ReadOnlySpan<T> лучше T[], List<T> лучше IEnumerable<T>. Между массивом и List<T> предпочтения нет — неоднозначность. Практический вывод для автора API: добавление перегрузки Foo(ReadOnlySpan<int>) к Foo(int[]) молча переключит вызовы Foo([1, 2, 3]) на неё; если у новой перегрузки другая семантика (например, хранит ссылку), это изменение поведения.

13.6. Свой тип: CollectionBuilder

Тип, который хочет принимать […], объявляет метод-фабрику:

chapters/13-collection-expressions/final/Bag.cs
// Свой тип: компилятор вызовет Bag.Create(ReadOnlySpan<T>)
[CollectionBuilder(typeof(Bag), nameof(Bag.Create))]
public sealed class Bag<T> : IEnumerable<T>
{
    readonly T[] _items;
    public Bag(ReadOnlySpan<T> items) => _items = items.ToArray();
    public int Count => _items.Length;
    public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)_items).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

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

В chapters/13-collection-expressions/start/Bag2.cs — TODO (строка 8): создать Bag из items (подсказка: у Bag есть конструктор от ReadOnlySpan).

Сделайте это до того, как смотреть решение в листинге ниже. Опыт 5 должен показать Count = 3.

chapters/13-collection-expressions/final/Bag2.cs
4
5
6
7
public static class Bag
{
    public static Bag<T> Create<T>(ReadOnlySpan<T> items) => new(items);
}

Требования: тип реализует IEnumerable<T>; атрибут указывает класс-владелец и имя метода; метод принимает ReadOnlySpan<T> и возвращает тип (допустимы обобщённые варианты Create<T>). Что получит Create, видно в IL (опыт 5):

  • для констант (Bag<int> b = [1, 2, 3]) — RuntimeHelpers.CreateSpan по статическим данным, без копирования на стороне вызова;
  • для переменных — InlineArray3<int> на стеке и InlineArrayAsReadOnlySpan.

Копия в куче появляется только там, где Create её делает: у Bag — items.ToArray() в конструкторе (64 байта выше). ImmutableArray<T> и ImmutableList<T> из BCL используют именно этот механизм; ImmutableArray.Create(ReadOnlySpan<T>) — их builder-метод.

Что проверить

Создайте тип FixedBuffer<T> с Create(ReadOnlySpan<T>), внутри которого Create копирует элементы в InlineArray, а не в кучу, и убедитесь по GetAllocatedBytesForCurrentThread, что FixedBuffer<int> f = [a, b, 3] не выделяет ничего.

13.7. Время: что экономит выражение

ListBuildBench: список из десяти значений-переменных (два прогона):

Способ Время Выделено
List<int> = [a, …, j] 32–33 нс 96 Б
new List<int>(10) { a, …, j } 46–50 нс 96 Б
new List<int>(new[] { a, …, j }) 39–43 нс 160 Б
new List<int> { a, …, j } 99–104 нс (3,1×) 216 Б

Выражение — в 3 раза быстрее обычного collection initializer (рост 4 → 8 → 16 вместо точной ёмкости) и в 1,4–1,5 раза быстрее инициализатора с готовой ёмкостью: запись элементов через Span вместо Add с проверками версии и границ.

А вот таблица констант (ConstTableBench, 1000 обращений по индексу):

Способ Время Выделено
static readonly int[] Table 485–492 нс 0
static ReadOnlySpan<int> Table => [...], каждый раз 478–482 нс 0
то же, один раз в локальную переменную 483–486 нс 0
int[] Make() => [...] (новый массив на вызов) 17,6–19,3 нс на вызов 88 Б

Свойство, возвращающее ReadOnlySpan<int>, не медленнее статического массива и ничего не хранит в куче — это рекомендуемый вид «таблицы констант». Выражение, возвращающее массив, создаёт новый массив при каждом вызове.

13.8. Аргументы выражения коллекции: with(...) .NET 10 — превью

В C# 15 готовится возможность передать аргументы конструктору прямо в выражении: [with(capacity: 10), 1, 2, 3] или [with(StringComparer.OrdinalIgnoreCase), "a", "A", "b"]. На стенде (SDK 10.0.401, LangVersion=preview; без превью — ошибка CS8652 «collection expression arguments» недоступна):

   List<int> l = [with(capacity: 10), 1, 2, 3];   -> Count 3, Capacity 10
   HashSet<string> h = [with(StringComparer.OrdinalIgnoreCase), "a", "A", "b"];   -> Count 2
   int[] a = [with(), 1];   -> ошибка CS9355: 'with(...)' elements are not supported for type 'int[]'
   Dictionary<string,int> d = [with(...), new("a", 1)];   -> CS9215: нужен Add с одним аргументом

Это закрывает главную претензию из §13.3: HashSet без ёмкости и без comparer'а. Синтаксис и состав возможностей в превью могут измениться; в проект лабораторной эти примеры не включены (нужен LangVersion=preview).

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

  • Выражение коллекции — не тип, а способ построения: код выбирается по целевому типу.
  • ReadOnlySpan<T>: константы — статические данные образа (0 байт, адрес один и тот же при каждом вызове, опыт 3); переменные — InlineArrayN на стеке. int[] — всегда новый массив ([] — Array.Empty).
  • List<T> — точная ёмкость + SetCount + запись в Span: в 3 раза быстрее collection initializer. HashSet<T> и прочие — initializer без ёмкости.
  • IEnumerable<T>/IReadOnlyList<T> — генерируемая <>z__ReadOnlyArray<T>: is IList<T> истинно, запись — NotSupportedException.
  • Spread по int[], List<T>, span — блочное копирование и ручной код не нужен; по IEnumerable<T> — промежуточный List и вторая копия (11–19× медленнее).
  • params ReadOnlySpan<T> — ноль аллокаций гарантированно; params int[] — 40 байт (ноль только при escape analysis); params IEnumerable<T> — самое дорогое.
  • Перегрузка ReadOnlySpan<T> предпочитается массиву и может молча переключить вызовы.
  • [CollectionBuilder] + Create(ReadOnlySpan<T>) — свой тип получает данные без аллокации на стороне вызова.
  • В Tier0 константный массив выделяет на 72 байта больше; прогревайте перед замером.

13.10. Практикум

Лабораторная: свой builder

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

dotnet run -c Release --project 13-collection-expressions\start

Задание 2. Выполните TODO в chapters/13-collection-expressions/start/Bag2.cs: реализуйте Bag.Create. Опыт 5 должен показать Count = 3.

Задание 3. Для каждого из методов Samples предскажите IL (newarr, CreateSpan, InlineArrayN, SetCount, <>z__ReadOnlyArray) и проверьте:

.\tools\disasm.ps1 -Project .\13-collection-expressions\final -Mode il -Type Samples

Задание 4. Сколько байт выделит int[] r = [.. list, .. other], где list — List<int> из 1000 элементов, other — int[] из 1000? Проверьте опытом и найдите в IL AsSpan.

Задание 5. Напишите метод Describe(IEnumerable<int> items), который по items is IList<int> l && !l.IsReadOnly решает, можно ли записывать. Что он решит для IEnumerable<int> x = [1, 2, 3] и для List<int>?

Задание 6. Реализуйте FixedBuffer<T> из §13.6 с [InlineArray(8)] и убедитесь, что FixedBuffer<int> f = [a, b] ничего не выделяет.

Ответы

1. Чаще всего ошибаются: «IEnumerable<int> x = [1, 2, 3] — это List<int>» (нет, <>z__ReadOnlyArray), «ReadOnlySpan<int> s = [1, 2, 3] выделяет 40 байт» (0), «[.. src, 4] для IEnumerable — одна аллокация» (три: список, рост, массив), «params int[] всегда выделяет» (нет, зависит от встраивания).

2. new(items) — конструктор Bag<T> принимает ReadOnlySpan<T>.

3. Ожидаемые ответы — в таблице §13.2: newarr+InitializeArray для константного массива, CreateSpan для ReadOnlySpan с константами, InlineArray3 для переменных.

4. int[] r = [.. list, .. other] — один new int[2000] (около 8 КБ) и два CopyTo; AsSpan(list) виден в IL. Промежуточных списков нет: длина известна статически.

5. Для <>z__ReadOnlyArray IsReadOnly = True → «писать нельзя»; для List<int> — False. Проверка is IList<int> одна не годится: нужен ещё !IsReadOnly.

6. [InlineArray(8)] struct Buf8<T> { T _e0; } — внутри FixedBuffer<T> поле Buf8<T>, Create копирует items в Span<T> из него. Объект FixedBuffer<T> — класс (аллокация 24+ байт), поэтому сделайте его struct, иначе «ноль байт» не получится.

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

using System.Runtime.CompilerServices;

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

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 1. Во что превращается [1, 2, 3] для разных целевых типов ==");
{
    // PREDICT: какой тип у IEnumerable<int> x = [1, 2, 3]? Можно ли привести его к List<int>? К IList<int>?
    void Show(string target, object o)
    {
        var t = o.GetType();
        string ro = o is IList<int> il ? $", IList.IsReadOnly = {il.IsReadOnly}" : "";
        Console.WriteLine($"   {target,-22} -> {t.Name}{ro}");
    }

    Show("int[]", Samples.ArrayConst());
    Show("List<int>", Samples.ListConst());
    Show("IEnumerable<int>", Samples.EnumerableConst());
    Show("IReadOnlyList<int>", Samples.ReadOnlyListVar(1, 2));
    Show("ICollection<int>", Samples.CollectionConst());
    Show("IList<int>", Samples.ListInterfaceConst());
    Show("HashSet<int>", Samples.HashSetConst());
    Show("IEnumerable<int> (пустой)", Samples.EnumerableEmpty());

    var e = Samples.EnumerableConst();
    Console.WriteLine($"   IEnumerable<int> x = [1,2,3]: is List<int> = {e is List<int>}, is int[] = {e is int[]}, is IList<int> = {e is IList<int>}");
    try { ((IList<int>)e)[0] = 9; }
    catch (NotSupportedException ex) { Console.WriteLine($"   запись по индексу: {ex.GetType().Name}"); }
    try { ((ICollection<int>)e).Add(4); }
    catch (NotSupportedException ex) { Console.WriteLine($"   Add: {ex.GetType().Name}"); }
    var t = e.GetType();
    Console.WriteLine($"   интерфейсы {t.Name}: {string.Join(", ", t.GetInterfaces().Select(i => i.Name))}\n");
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 2. Сколько байт выделяет каждый вариант ==");
{
    var arr = new[] { 5, 6, 7, 8 };
    var list = new List<int>(arr);
    IEnumerable<int> asEnumerable = arr;                 // под ним массив
    IEnumerable<int> lazy = arr.Where(x => x > 0);       // итератор LINQ

    long B(Action a) => Measure.Bytes(a);
    // Константный массив до прогрева: Tier0 выделяет больше (метод ещё не оптимизирован)
    long cold = Measure.Cold(() => Samples.ArrayEmpty());   // прогрев пустым
    long coldConst = Measure.Cold(() => Samples.ArrayConst());
    long coldEnum = Measure.Cold(() => Samples.EnumerableConst());
    // PREDICT: что из этого не выделит ни байта?
    var rows = new (string Name, long Bytes)[]
    {
        ("int[] = [1,2,3]",                      B(() => Samples.ArrayConst())),
        ("int[] = [a,b,3]",                      B(() => Samples.ArrayVar(1, 2))),
        ("int[] = []",                           B(() => Samples.ArrayEmpty())),
        ("List<int> = [1,2,3]",                  B(() => Samples.ListConst())),
        ("new List<int> { 1, 2, 3 }",            B(() => Samples.NewListInitializer())),
        ("ReadOnlySpan<int> = [1,2,3]",          B(() => Samples.SpanConst())),
        ("ReadOnlySpan<int> = [a,b,3]",          B(() => Samples.SpanVarSum(1, 2))),
        ("Span<int> = [a,b,3]",                  B(() => Samples.SpanMutableSum(1, 2))),
        ("IEnumerable<int> = [1,2,3]",           B(() => Samples.EnumerableConst())),
        ("IEnumerable<int> = []",                B(() => Samples.EnumerableEmpty())),
        ("HashSet<int> = [1,2,2,3]",             B(() => Samples.HashSetConst())),
        ("ImmutableArray<int> = [a,b,3]",        B(() => Samples.ImmutableArrayVar(1, 2))),
    };
    foreach (var (name, bytes) in rows) Console.WriteLine($"   {name,-34} {bytes,5} Б");
    Console.WriteLine($"   (до прогрева, Tier0: int[] = [1,2,3] — {coldConst} Б, IEnumerable<int> = [1,2,3] — {coldEnum} Б)");

    Console.WriteLine("   --- spread ---");
    Console.WriteLine($"   [..int[4], 4]                        {B(() => Samples.ArraySpreadArray(arr)),5} Б");
    Console.WriteLine($"   [..List<int>(4), 4]                  {B(() => Samples.ArraySpreadList(list)),5} Б");
    Console.WriteLine($"   [..IEnumerable<int> (массив), 4]     {B(() => Samples.ArraySpreadEnumerable(asEnumerable)),5} Б");
    Console.WriteLine($"   [..Where(...), 4] (итератор LINQ)    {B(() => Samples.SpreadWhere(arr)),5} Б");
    Console.WriteLine($"   List<int> = [..int[4], 4]            {B(() => Samples.ListSpreadArray(arr)),5} Б");
    Console.WriteLine($"   List<int> = [..IEnumerable (лень), 4]{B(() => Samples.ListSpreadEnumerable(lazy)),5} Б");

    Console.WriteLine("   --- params ---");
    Console.WriteLine($"   SumArray(a, b, 3)       params int[]            {B(() => Samples.CallArray(1, 2)),5} Б");
    Console.WriteLine($"   SumSpan(a, b, 3)        params ReadOnlySpan<int>{B(() => Samples.CallSpan(1, 2)),5} Б");
    Console.WriteLine($"   SumEnumerable(a, b, 3)  params IEnumerable<int> {B(() => Samples.CallEnumerable(1, 2)),5} Б\n");
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 3. Константы в ReadOnlySpan<int> — статические данные ==");
unsafe
{
    // PREDICT: одинаковы ли адреса данных у двух вызовов SpanConst()? А у двух вызовов ArrayConst()?
    var s1 = Samples.SpanConst();
    var s2 = Samples.SpanConst();
    fixed (int* p1 = s1) fixed (int* p2 = s2)
        Console.WriteLine($"   SpanConst() дважды: один и тот же адрес = {p1 == p2}");

    var a1 = Samples.ArrayConst();
    var a2 = Samples.ArrayConst();
    Console.WriteLine($"   ArrayConst() дважды: один и тот же массив = {ReferenceEquals(a1, a2)}");
    Console.WriteLine();
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 4. Выбор перегрузки ==");
{
    // PREDICT: какую перегрузку выберет компилятор?
    Console.WriteLine($"   A(int[]) / A(ReadOnlySpan<int>)        <- [1,2,3]: {Overloads.A([1, 2, 3])}");
    Console.WriteLine($"   B(List<int>) / B(IEnumerable<int>)     <- [1,2,3]: {Overloads.B([1, 2, 3])}");
    Console.WriteLine($"   C(int[]) / C(List<int>) — неоднозначно? — вызов закомментирован");
    // Overloads.C([1, 2, 3]);   // CS0121: неоднозначный вызов
    Console.WriteLine();
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 5. Свой тип: CollectionBuilder ==");
{
    try
    {
        var bag = Samples.BagConst();
        Console.WriteLine($"   Bag<int> = [1,2,3]: Count = {bag.Count}, тип = {bag.GetType().Name}");
    }
    catch (NotImplementedException e)
    {
        Console.WriteLine($"   пока не реализовано: {e.Message}");
    }
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 6. Семантика: spread — копия, порядок вычисления ==");
{
    var src = new List<int> { 1, 2, 3 };
    List<int> copy = [.. src];
    src.Add(99);
    Console.WriteLine($"   copy после src.Add(99): [{string.Join(",", copy)}] (копия)");

    int calls = 0;
    int Next() => ++calls;
    int[] ordered = [Next(), Next(), .. new[] { Next(), Next() }, Next()];
    Console.WriteLine($"   порядок вычисления элементов: [{string.Join(",", ordered)}] (слева направо)");

    var nested = new int[][] { [1, 2], [3], [] };
    int[] flat = [.. nested.SelectMany(a => a)];
    Console.WriteLine($"   [.. SelectMany]: [{string.Join(",", flat)}]");
}
using System.Collections;
using System.Runtime.CompilerServices;

// Свой тип: компилятор вызовет Bag.Create(ReadOnlySpan<T>)
[CollectionBuilder(typeof(Bag), nameof(Bag.Create))]
public sealed class Bag<T> : IEnumerable<T>
{
    readonly T[] _items;
    public Bag(ReadOnlySpan<T> items) => _items = items.ToArray();
    public int Count => _items.Length;
    public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)_items).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
using System.Collections.Immutable;
using System.Runtime.CompilerServices;

public static class Bag
{
    public static Bag<T> Create<T>(ReadOnlySpan<T> items)
    {
        // TODO: создать Bag<T> из items (подсказка: у Bag<T> есть конструктор от ReadOnlySpan<T>)
        throw new NotImplementedException("TODO: Bag.Create");
    }
}
using System.Runtime.CompilerServices;

static class Measure
{
    // Среднее по 10 вызовам сразу после первого: метод ещё не перекомпилирован (Tier0)
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static long Cold(Action action)
    {
        action();
        long before = GC.GetAllocatedBytesForCurrentThread();
        for (int i = 0; i < 10; i++) action();
        return (GC.GetAllocatedBytesForCurrentThread() - before) / 10;
    }

    // После прогрева: 150 вызовов с паузами, чтобы фоновая компиляция успела поставить Tier1
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static long Bytes(Action action)
    {
        for (int r = 0; r < 3; r++)
        {
            for (int i = 0; i < 50; i++) action();
            Thread.Sleep(150);
        }
        long before = GC.GetAllocatedBytesForCurrentThread();
        action();
        return GC.GetAllocatedBytesForCurrentThread() - before;
    }
}
using System.Collections.Immutable;
using System.Runtime.CompilerServices;

// Перегрузки: какую выберет компилятор для [1, 2, 3]
public static class Overloads
{
    public static string A(int[] _) => "int[]";
    public static string A(ReadOnlySpan<int> _) => "ReadOnlySpan<int>";

    public static string B(List<int> _) => "List<int>";
    public static string B(IEnumerable<int> _) => "IEnumerable<int>";

    public static string C(int[] _) => "int[]";
    public static string C(List<int> _) => "List<int>";
}
using System.Collections.Immutable;
using System.Runtime.CompilerServices;

// Каждый метод — один целевой тип: смотрим, во что компилятор превращает [ ... ]
public static class Samples
{
    // --- массив ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadArray(int[] src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadList(List<int> src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadEnumerable(IEnumerable<int> src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayEmpty() => [];

    // --- List<T> ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListSpreadArray(int[] src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListSpreadEnumerable(IEnumerable<int> src) => [.. src, 4];

    // --- span ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static ReadOnlySpan<int> SpanConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int SpanVarSum(int a, int b)
    {
        ReadOnlySpan<int> s = [a, b, 3];     // не выходит из метода: место можно взять на стеке
        int sum = 0;
        foreach (var x in s) sum += x;
        return sum;
    }

    // --- интерфейсные целевые типы ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static IEnumerable<int> EnumerableConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static IReadOnlyList<int> ReadOnlyListVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static ICollection<int> CollectionConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static IList<int> ListInterfaceConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static IEnumerable<int> EnumerableEmpty() => [];

    // --- прочие типы ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static HashSet<int> HashSetConst() => [1, 2, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static ImmutableArray<int> ImmutableArrayVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static Queue<int> QueueConst() => new([1, 2, 3]);

    // --- params ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static int SumArray(params int[] v) { int s = 0; foreach (var x in v) s += x; return s; }
    [MethodImpl(MethodImplOptions.NoInlining)] public static int SumSpan(params ReadOnlySpan<int> v) { int s = 0; foreach (var x in v) s += x; return s; }
    [MethodImpl(MethodImplOptions.NoInlining)] public static int SumEnumerable(params IEnumerable<int> v) { int s = 0; foreach (var x in v) s += x; return s; }

    [MethodImpl(MethodImplOptions.NoInlining)] public static int CallArray(int a, int b) => SumArray(a, b, 3);
    [MethodImpl(MethodImplOptions.NoInlining)] public static int CallSpan(int a, int b) => SumSpan(a, b, 3);
    [MethodImpl(MethodImplOptions.NoInlining)] public static int CallEnumerable(int a, int b) => SumEnumerable(a, b, 3);

    // --- ещё случаи ---
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int SpanMutableSum(int a, int b)
    {
        Span<int> s = [a, b, 3];             // изменяемый span: статические данные не годятся
        s[0] = 10;
        int sum = 0;
        foreach (var x in s) sum += x;
        return sum;
    }

    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] SpreadWhere(IEnumerable<int> src) => [.. src.Where(x => x > 0), 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] SpreadTwoArrays(int[] a, int[] b) => [.. a, .. b];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> NewListInitializer() => new List<int> { 1, 2, 3 };
    [MethodImpl(MethodImplOptions.NoInlining)] public static Bag<int> BagConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static Bag<int> BagVar(int a, int b) => [a, b, 3];
}
using System.Runtime.CompilerServices;

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

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 1. Во что превращается [1, 2, 3] для разных целевых типов ==");
{
    // PREDICT: какой тип у IEnumerable<int> x = [1, 2, 3]? Можно ли привести его к List<int>? К IList<int>?
    void Show(string target, object o)
    {
        var t = o.GetType();
        string ro = o is IList<int> il ? $", IList.IsReadOnly = {il.IsReadOnly}" : "";
        Console.WriteLine($"   {target,-22} -> {t.Name}{ro}");
    }

    Show("int[]", Samples.ArrayConst());
    Show("List<int>", Samples.ListConst());
    Show("IEnumerable<int>", Samples.EnumerableConst());
    Show("IReadOnlyList<int>", Samples.ReadOnlyListVar(1, 2));
    Show("ICollection<int>", Samples.CollectionConst());
    Show("IList<int>", Samples.ListInterfaceConst());
    Show("HashSet<int>", Samples.HashSetConst());
    Show("IEnumerable<int> (пустой)", Samples.EnumerableEmpty());

    var e = Samples.EnumerableConst();
    Console.WriteLine($"   IEnumerable<int> x = [1,2,3]: is List<int> = {e is List<int>}, is int[] = {e is int[]}, is IList<int> = {e is IList<int>}");
    try { ((IList<int>)e)[0] = 9; }
    catch (NotSupportedException ex) { Console.WriteLine($"   запись по индексу: {ex.GetType().Name}"); }
    try { ((ICollection<int>)e).Add(4); }
    catch (NotSupportedException ex) { Console.WriteLine($"   Add: {ex.GetType().Name}"); }
    var t = e.GetType();
    Console.WriteLine($"   интерфейсы {t.Name}: {string.Join(", ", t.GetInterfaces().Select(i => i.Name))}\n");
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 2. Сколько байт выделяет каждый вариант ==");
{
    var arr = new[] { 5, 6, 7, 8 };
    var list = new List<int>(arr);
    IEnumerable<int> asEnumerable = arr;                 // под ним массив
    IEnumerable<int> lazy = arr.Where(x => x > 0);       // итератор LINQ

    long B(Action a) => Measure.Bytes(a);
    // Константный массив до прогрева: Tier0 выделяет больше (метод ещё не оптимизирован)
    long cold = Measure.Cold(() => Samples.ArrayEmpty());   // прогрев пустым
    long coldConst = Measure.Cold(() => Samples.ArrayConst());
    long coldEnum = Measure.Cold(() => Samples.EnumerableConst());
    // PREDICT: что из этого не выделит ни байта?
    var rows = new (string Name, long Bytes)[]
    {
        ("int[] = [1,2,3]",                      B(() => Samples.ArrayConst())),
        ("int[] = [a,b,3]",                      B(() => Samples.ArrayVar(1, 2))),
        ("int[] = []",                           B(() => Samples.ArrayEmpty())),
        ("List<int> = [1,2,3]",                  B(() => Samples.ListConst())),
        ("new List<int> { 1, 2, 3 }",            B(() => Samples.NewListInitializer())),
        ("ReadOnlySpan<int> = [1,2,3]",          B(() => Samples.SpanConst())),
        ("ReadOnlySpan<int> = [a,b,3]",          B(() => Samples.SpanVarSum(1, 2))),
        ("Span<int> = [a,b,3]",                  B(() => Samples.SpanMutableSum(1, 2))),
        ("IEnumerable<int> = [1,2,3]",           B(() => Samples.EnumerableConst())),
        ("IEnumerable<int> = []",                B(() => Samples.EnumerableEmpty())),
        ("HashSet<int> = [1,2,2,3]",             B(() => Samples.HashSetConst())),
        ("ImmutableArray<int> = [a,b,3]",        B(() => Samples.ImmutableArrayVar(1, 2))),
        ("Bag<int> = [1,2,3] (builder)",         B(() => Samples.BagConst())),
        ("Bag<int> = [a,b,3] (builder)",         B(() => Samples.BagVar(1, 2))),
    };
    foreach (var (name, bytes) in rows) Console.WriteLine($"   {name,-34} {bytes,5} Б");
    Console.WriteLine($"   (до прогрева, Tier0: int[] = [1,2,3] — {coldConst} Б, IEnumerable<int> = [1,2,3] — {coldEnum} Б)");

    Console.WriteLine("   --- spread ---");
    Console.WriteLine($"   [..int[4], 4]                        {B(() => Samples.ArraySpreadArray(arr)),5} Б");
    Console.WriteLine($"   [..List<int>(4), 4]                  {B(() => Samples.ArraySpreadList(list)),5} Б");
    Console.WriteLine($"   [..IEnumerable<int> (массив), 4]     {B(() => Samples.ArraySpreadEnumerable(asEnumerable)),5} Б");
    Console.WriteLine($"   [..Where(...), 4] (итератор LINQ)    {B(() => Samples.SpreadWhere(arr)),5} Б");
    Console.WriteLine($"   List<int> = [..int[4], 4]            {B(() => Samples.ListSpreadArray(arr)),5} Б");
    Console.WriteLine($"   List<int> = [..IEnumerable (лень), 4]{B(() => Samples.ListSpreadEnumerable(lazy)),5} Б");

    Console.WriteLine("   --- params ---");
    Console.WriteLine($"   SumArray(a, b, 3)       params int[]            {B(() => Samples.CallArray(1, 2)),5} Б");
    Console.WriteLine($"   SumSpan(a, b, 3)        params ReadOnlySpan<int>{B(() => Samples.CallSpan(1, 2)),5} Б");
    Console.WriteLine($"   SumEnumerable(a, b, 3)  params IEnumerable<int> {B(() => Samples.CallEnumerable(1, 2)),5} Б\n");
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 3. Константы в ReadOnlySpan<int> — статические данные ==");
unsafe
{
    // PREDICT: одинаковы ли адреса данных у двух вызовов SpanConst()? А у двух вызовов ArrayConst()?
    var s1 = Samples.SpanConst();
    var s2 = Samples.SpanConst();
    fixed (int* p1 = s1) fixed (int* p2 = s2)
        Console.WriteLine($"   SpanConst() дважды: один и тот же адрес = {p1 == p2}");

    var a1 = Samples.ArrayConst();
    var a2 = Samples.ArrayConst();
    Console.WriteLine($"   ArrayConst() дважды: один и тот же массив = {ReferenceEquals(a1, a2)}");
    Console.WriteLine();
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 4. Выбор перегрузки ==");
{
    // PREDICT: какую перегрузку выберет компилятор?
    Console.WriteLine($"   A(int[]) / A(ReadOnlySpan<int>)        <- [1,2,3]: {Overloads.A([1, 2, 3])}");
    Console.WriteLine($"   B(List<int>) / B(IEnumerable<int>)     <- [1,2,3]: {Overloads.B([1, 2, 3])}");
    Console.WriteLine($"   C(int[]) / C(List<int>) — неоднозначно? — вызов закомментирован");
    // Overloads.C([1, 2, 3]);   // CS0121: неоднозначный вызов
    Console.WriteLine();
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 5. Свой тип: CollectionBuilder ==");
{
    var bag = Samples.BagConst();
    Console.WriteLine($"   Bag<int> = [1,2,3]: Count = {bag.Count}, тип = {bag.GetType().Name}");
    Console.WriteLine($"   Bag<int> = [a,b,3] с builder'ом: Create получает ReadOnlySpan<int> — буфер на стеке, массив в конструкторе Bag — копия\n");
}

// ---------------------------------------------------------------------------------------------
Console.WriteLine("== Опыт 6. Семантика: spread — копия, порядок вычисления ==");
{
    var src = new List<int> { 1, 2, 3 };
    List<int> copy = [.. src];
    src.Add(99);
    Console.WriteLine($"   copy после src.Add(99): [{string.Join(",", copy)}] (копия)");

    int calls = 0;
    int Next() => ++calls;
    int[] ordered = [Next(), Next(), .. new[] { Next(), Next() }, Next()];
    Console.WriteLine($"   порядок вычисления элементов: [{string.Join(",", ordered)}] (слева направо)");

    var nested = new int[][] { [1, 2], [3], [] };
    int[] flat = [.. nested.SelectMany(a => a)];
    Console.WriteLine($"   [.. SelectMany]: [{string.Join(",", flat)}]");
}
using System.Collections;
using System.Runtime.CompilerServices;

// Свой тип: компилятор вызовет Bag.Create(ReadOnlySpan<T>)
[CollectionBuilder(typeof(Bag), nameof(Bag.Create))]
public sealed class Bag<T> : IEnumerable<T>
{
    readonly T[] _items;
    public Bag(ReadOnlySpan<T> items) => _items = items.ToArray();
    public int Count => _items.Length;
    public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)_items).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
1
2
3
4
5
6
7
using System.Collections.Immutable;
using System.Runtime.CompilerServices;

public static class Bag
{
    public static Bag<T> Create<T>(ReadOnlySpan<T> items) => new(items);
}
using System.Runtime.CompilerServices;

static class Measure
{
    // Среднее по 10 вызовам сразу после первого: метод ещё не перекомпилирован (Tier0)
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static long Cold(Action action)
    {
        action();
        long before = GC.GetAllocatedBytesForCurrentThread();
        for (int i = 0; i < 10; i++) action();
        return (GC.GetAllocatedBytesForCurrentThread() - before) / 10;
    }

    // После прогрева: 150 вызовов с паузами, чтобы фоновая компиляция успела поставить Tier1
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static long Bytes(Action action)
    {
        for (int r = 0; r < 3; r++)
        {
            for (int i = 0; i < 50; i++) action();
            Thread.Sleep(150);
        }
        long before = GC.GetAllocatedBytesForCurrentThread();
        action();
        return GC.GetAllocatedBytesForCurrentThread() - before;
    }
}
using System.Collections.Immutable;
using System.Runtime.CompilerServices;

// Перегрузки: какую выберет компилятор для [1, 2, 3]
public static class Overloads
{
    public static string A(int[] _) => "int[]";
    public static string A(ReadOnlySpan<int> _) => "ReadOnlySpan<int>";

    public static string B(List<int> _) => "List<int>";
    public static string B(IEnumerable<int> _) => "IEnumerable<int>";

    public static string C(int[] _) => "int[]";
    public static string C(List<int> _) => "List<int>";
}
using System.Collections.Immutable;
using System.Runtime.CompilerServices;

// Каждый метод — один целевой тип: смотрим, во что компилятор превращает [ ... ]
public static class Samples
{
    // --- массив ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadArray(int[] src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadList(List<int> src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArraySpreadEnumerable(IEnumerable<int> src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] ArrayEmpty() => [];

    // --- List<T> ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListSpreadArray(int[] src) => [.. src, 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> ListSpreadEnumerable(IEnumerable<int> src) => [.. src, 4];

    // --- span ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static ReadOnlySpan<int> SpanConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int SpanVarSum(int a, int b)
    {
        ReadOnlySpan<int> s = [a, b, 3];     // не выходит из метода: место можно взять на стеке
        int sum = 0;
        foreach (var x in s) sum += x;
        return sum;
    }

    // --- интерфейсные целевые типы ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static IEnumerable<int> EnumerableConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static IReadOnlyList<int> ReadOnlyListVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static ICollection<int> CollectionConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static IList<int> ListInterfaceConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static IEnumerable<int> EnumerableEmpty() => [];

    // --- прочие типы ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static HashSet<int> HashSetConst() => [1, 2, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static ImmutableArray<int> ImmutableArrayVar(int a, int b) => [a, b, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static Queue<int> QueueConst() => new([1, 2, 3]);

    // --- params ---
    [MethodImpl(MethodImplOptions.NoInlining)] public static int SumArray(params int[] v) { int s = 0; foreach (var x in v) s += x; return s; }
    [MethodImpl(MethodImplOptions.NoInlining)] public static int SumSpan(params ReadOnlySpan<int> v) { int s = 0; foreach (var x in v) s += x; return s; }
    [MethodImpl(MethodImplOptions.NoInlining)] public static int SumEnumerable(params IEnumerable<int> v) { int s = 0; foreach (var x in v) s += x; return s; }

    [MethodImpl(MethodImplOptions.NoInlining)] public static int CallArray(int a, int b) => SumArray(a, b, 3);
    [MethodImpl(MethodImplOptions.NoInlining)] public static int CallSpan(int a, int b) => SumSpan(a, b, 3);
    [MethodImpl(MethodImplOptions.NoInlining)] public static int CallEnumerable(int a, int b) => SumEnumerable(a, b, 3);

    // --- ещё случаи ---
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int SpanMutableSum(int a, int b)
    {
        Span<int> s = [a, b, 3];             // изменяемый span: статические данные не годятся
        s[0] = 10;
        int sum = 0;
        foreach (var x in s) sum += x;
        return sum;
    }

    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] SpreadWhere(IEnumerable<int> src) => [.. src.Where(x => x > 0), 4];
    [MethodImpl(MethodImplOptions.NoInlining)] public static int[] SpreadTwoArrays(int[] a, int[] b) => [.. a, .. b];
    [MethodImpl(MethodImplOptions.NoInlining)] public static List<int> NewListInitializer() => new List<int> { 1, 2, 3 };
    [MethodImpl(MethodImplOptions.NoInlining)] public static Bag<int> BagConst() => [1, 2, 3];
    [MethodImpl(MethodImplOptions.NoInlining)] public static Bag<int> BagVar(int a, int b) => [a, b, 3];
}
1
2
3
4
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

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

// Таблица констант: статический массив против ReadOnlySpan-свойства
[MemoryDiagnoser]
public class ConstTableBench
{
    static readonly int[] Table = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3];
    static ReadOnlySpan<int> SpanTable => [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3];

    int[] _idx = null!;

    [GlobalSetup]
    public void Setup()
    {
        var r = new Random(1);
        _idx = Enumerable.Range(0, 1000).Select(_ => r.Next(16)).ToArray();
    }

    [Benchmark(Baseline = true)]
    public int StaticArray()
    {
        int s = 0;
        foreach (var i in _idx) s += Table[i];
        return s;
    }

    [Benchmark]
    public int SpanPropertyEachTime()
    {
        int s = 0;
        foreach (var i in _idx) s += SpanTable[i];
        return s;
    }

    [Benchmark]
    public int SpanPropertyOnce()
    {
        int s = 0;
        var t = SpanTable;
        foreach (var i in _idx) s += t[i];
        return s;
    }

    [Benchmark]
    public int[] NewArrayEachCall() => [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3];
}
using BenchmarkDotNet.Attributes;

// Собрать список из десяти значений-переменных
[MemoryDiagnoser]
public class ListBuildBench
{
    int _a = 1, _b = 2, _c = 3, _d = 4, _e = 5, _f = 6, _g = 7, _h = 8, _i = 9, _j = 10;

    [Benchmark(Baseline = true)]
    public List<int> CollectionExpression() => [_a, _b, _c, _d, _e, _f, _g, _h, _i, _j];

    [Benchmark]
    public List<int> CollectionInitializer() => new List<int> { _a, _b, _c, _d, _e, _f, _g, _h, _i, _j };

    [Benchmark]
    public List<int> InitializerWithCapacity() => new List<int>(10) { _a, _b, _c, _d, _e, _f, _g, _h, _i, _j };

    [Benchmark]
    public List<int> FromArray() => new List<int>(new[] { _a, _b, _c, _d, _e, _f, _g, _h, _i, _j });
}
using BenchmarkDotNet.Attributes;

// params с тремя значениями
[MemoryDiagnoser]
public class ParamsBench
{
    int _a = 1, _b = 2, _c = 3;

    static int SumArray(params int[] v) { int s = 0; foreach (var x in v) s += x; return s; }
    static int SumSpan(params ReadOnlySpan<int> v) { int s = 0; foreach (var x in v) s += x; return s; }
    static int SumEnumerable(params IEnumerable<int> v) { int s = 0; foreach (var x in v) s += x; return s; }

    [Benchmark(Baseline = true)]
    public int ParamsArray() => SumArray(_a, _b, _c);

    [Benchmark]
    public int ParamsSpan() => SumSpan(_a, _b, _c);

    [Benchmark]
    public int ParamsEnumerable() => SumEnumerable(_a, _b, _c);

    [Benchmark]
    public int ParamsArrayConstants() => SumArray(1, 2, 3);

    [Benchmark]
    public int ParamsSpanConstants() => SumSpan(1, 2, 3);
}
using BenchmarkDotNet.Attributes;

// Склеить два массива
[MemoryDiagnoser]
public class SpreadBench
{
    [Params(100, 10_000)]
    public int N;

    int[] _a = null!, _b = null!;

    [GlobalSetup]
    public void Setup()
    {
        _a = Enumerable.Range(0, N).ToArray();
        _b = Enumerable.Range(N, N).ToArray();
    }

    [Benchmark(Baseline = true)]
    public int[] SpreadExpression() => [.. _a, .. _b];

    [Benchmark]
    public int[] LinqConcatToArray() => _a.Concat(_b).ToArray();

    [Benchmark]
    public int[] ManualCopy()
    {
        var r = new int[_a.Length + _b.Length];
        Array.Copy(_a, r, _a.Length);
        Array.Copy(_b, 0, r, _a.Length, _b.Length);
        return r;
    }

    [Benchmark]
    public int[] ListAddRangeToArray()
    {
        var l = new List<int>();
        l.AddRange(_a);
        l.AddRange(_b);
        return l.ToArray();
    }

    [Benchmark]
    public int[] SpreadOfLazySequence() => [.. _a.Where(x => x >= 0), .. _b];
}