Skip to content

Traverse every contiguous collection through one storage view, one loop per element kind #355

Open
0 of 11 issues completed

Description

@JasonXuDeveloper

The goal in one line: every collection is the same thing at the bottom. A collection is storage holding elements: contiguous, a ring, strided entries, segments, or nodes gathered into runs. An element is written and read by its kind, decided once. There is one storage contract, one element loop per direction, and one kind decision. Everything a single collection or type does differently is a thin layer over these, falling back to them.

The rules this design keeps (agreed in the comments below):

  • No special loops per collection or per element shape. There is no pair loop and no list loop. A dictionary's entries are strided elements whose element is the pair.
  • Composite elements compose their kind from their members. This covers KeyValuePair, ValueTuple/Tuple of any arity, and user generic [NinoType] structs and classes. All members raw → raw. All members fixed size → a composed block (Make every fixed-size formatter a block formatter, and let blocks compose #348). Otherwise each member takes its own path, with a polymorphic member's dispatch inline. (comment)
  • "Raw" means this runtime's memory layout equals the wire layout, decided by Nino's existing layout check (the canonical 64-bit CoreCLR layout, padding zeroed). It never means unmanaged. ValueTuple and KeyValuePair are auto-layout on CoreCLR, and Unity/Mono/IL2CPP lay some types out differently. Such types take the block path and write the same bytes everywhere.
  • A polymorphic base contributes only its per-value dispatch, inlined by the one loop. The per-base generated WriteElements and pair entry points go away, and the writer stays in a local.
  • One storage contract for BCL types, ICollection<T> and user types: segments to write; get a span, advance and complete to read. The BCL types reach it through internal accessors, ICollection<T> through an adapter, and user types through an optional public interface. (comment)
  • Devirtualized everywhere: constrained calls behind queries keyed on the formatter alone, with no is, no cast and no boxed field (Reach formatter capabilities through constrained calls, never interface casts #346, done). There are no generic default members on INinoFormatter<T>, because Unity 2022.3's IL2CPP fails on them (refactor(core)!: one generic pair loop for every key of a polymorphic dictionary #405).
  • Lands on feat/storage-layer, one pull request per step. It is tuned and A/B'd once, against main, when the branch merges.

Every collection whose memory is contiguous, or that is implemented over contiguous storage, shares one bottom-level mechanism:

  • arrays, List<T>, Span/Memory/ArraySegment, ImmutableArray;
  • Queue and Stack (rings and arrays);
  • HashSet and Dictionary (their entries arrays);
  • PriorityQueue (its heap), SortedList (its two arrays), Collection and ObservableCollection (the list they wrap);
  • the concurrent and immutable collections that hold arrays;
  • multi-dimensional arrays.

A collection describes its storage as a view: segments, each with a start, a count and a stride (an entry's size, so a Dictionary's entries are a strided run of KeyValuePair<TKey, TValue> once a startup check proves the entry lays its key and value out as KeyValuePair does), an in-use test for free lists, and wrap-around for rings. No key or value offset: the element is the whole T, and a composite's formatter composes its items (correction). Each element kind has one loop over that view, written once: raw blocks, block formatters, nullable slots, polymorphic values with the generated dispatch inline, strings and general formatters. Reads fill storage through the same view, keeping the hash-collision counting.

Devirtualized on .NET 8+ and on netstandard2.1 (IL2CPP, Mono): capabilities are reached by constrained calls on the formatter's struct type parameter, never an interface cast. Traits are static readonly fields where IL2CPP and Mono box an is test, and members generated into users' partial types where that removes a dispatch.

Non-contiguous collections use the same layer, segment by segment:

  • ReadOnlySequence<T>: each segment is a span;
  • LinkedList<T>, SortedSet and the immutable trees: runs of nodes, gathered into spans or walked node by node, whichever measures faster;
  • an IEnumerable<T> with no storage to reach: buffered into a span.

One decision per element type, taken once in one place (a static readonly trait per type and formatter, folded by the JIT on .NET 8+, read once on netstandard), with no per-collection copy of it:

  1. unmanaged / raw: one block with the SIMD kernels;
  2. T? of raw T, or NinoNullable<T>: the slot kernels;
  3. a block formatter (fixed size, composed): the block path;
  4. a class: polymorphic dispatch inline where the base dispatches, and prefetch under NinoPrefetch's gate;
  5. otherwise: the general formatter, reached by a constrained call.

Polymorphic dispatch is the most efficient form there is, with no virtual or indirect call per element on either target: the subtype test order, a cached last type, or another general form, chosen by measurement against LuminPack.

In every loop:

  • unmanaged contiguous elements (raw blocks, block formatters, nullable slots) take the existing SIMD kernels over the view, with a gather or scatter where entries are strided;
  • stores, or loads where that measured better, are aligned to the vector width or cache line; copies on AMD apply the 4K-aliasing rule (perf(core): copy downward on AMD where a forward copy hits 4K aliasing #326);
  • class elements, polymorphic and dictionary values included, prefetch in every collection kind under NinoPrefetch's gate, not only top-level arrays and lists.

Reads as much as writes, everywhere above: each element kind has one read loop and one write loop over the view.

  • Every loop aligns, not only the vector ones: unmanaged elements get SIMD, and everything else still aligns its stores (or loads) where that measures faster.
  • Gathering into a span (sequences, trees, linked lists, enumerables, values that must be reordered) reuses pooled memory (ArrayPool, the writer's own buffer, the ArrayBuffer of other runtimes) and copies at most a bounded number of elements per step, so a large collection never needs one huge buffer.
  • A new collection is built the fastest way its runtime allows, through its internals where runtime-internals proves the layout, with every hostile-input check kept:
    • Dictionary fills its entries and links the buckets in one pass after (done in perf(core): read a new dictionary's pairs into its entries and link the buckets after #390, LuminPack's form), keeping the collision count and the repeated- and null-key checks;
    • SortedSet builds its tree in one pass;
    • the same is sought for HashSet of every element kind, ConcurrentDictionary, SortedDictionary, SortedList, PriorityQueue, LinkedList and the immutable collections.
  • Dispatch stays under study until it is the fastest form with no virtual or indirect call per element, on .NET and on netstandard (IL2CPP, Mono).

This issue gathers #346, #347, #348, #349, #350, #295, #320 and #345 under one design. Done means fewer loops in total, each pull request with no method worse in the machine code and an A/B per CPU.


Generated by Claude Code

Sub-issues

Sub-issues

0 of 11 Issues completed
Loading 11 sub-issues

Activity

  1. added
    area: generator
    kind: perf
    kind: refactor
    area: core
    on Nov 16, 2026
  2. added this to the v4.0.0 milestone on Nov 16, 2026
  3. JasonXuDeveloper commented on Nov 16, 2026

    @JasonXuDeveloper
    OwnerAuthor

    Design, in order of pull requests. Each lands with tests, asm.py compare showing no method worse, a runner A/B per CPU, and the IL2CPP C++ and the Unity DLLs where it touches them. No pull request changes the bytes.

    In total, element-kind tests in about 60 places become one class, and about 57 per-element loops become 6 kinds × 2 directions plus one pair loop.


    Generated by Claude Code

  4. JasonXuDeveloper commented on Nov 16, 2026

    @JasonXuDeveloper
    OwnerAuthor

    The full design behind the plan above: the storage view, the per-kind loops, devirtualization on .NET 8+ and netstandard2.1, IL2CPP, LuminPack's mechanisms, the PR plan and its risks.

    The full document

    Design: one storage view, one loop per element kind (#355)

    Status: design only, nothing in the repository changed. Read on origin/main 9158f97 and on
    origin/claude/dictionary-pairs-general (abc2115). Every number here is either a runner number already in the skills
    (cited) or a local number marked "local", which guides the work and is never published.

    Contents

    1. What is there today (the inventory this design replaces)
    2. The abstraction: storage view = segments of cursors with a layout
    3. One decision per element type (NinoKind<T, TFormatter>), and where it is repeated today
    4. The per-element-kind loops, each written once, with SIMD, alignment and prefetch
    5. Reaching formatter capabilities: constrained calls, static readonly traits, IL2CPP, partial types
    6. Polymorphic dispatch per element: options and costs
    7. Every collection on the view (contiguous and not), and how each is fastest
    8. LuminPack: how it works, why it is fast, what fits Nino
    9. Migration plan: ordered pull requests, issue map, what each deletes, how each is measured
    10. Risks
    11. Decisions for the owner

    1. What is there today

    The element-kind decision and the loops are spread over the collection formatters. Counted on 9158f97:

    • Lines that call an element formatter or WriteOne/ReadOne/AddUnique inside a loop: 57 across 20 files
      (NinoDictionary 14, BclDictionaries 10, NinoElements 7, PriorityQueueFormatter 4, LookupFormatters 4,
      KeyValuePairFormatter 4, HashSetFormatter 3, BclCollections 3, DictionaryLikeFormatter 3, Immutable 5, ...),
      plus 4 hand-written string loops in Reader.Strings.cs (ReadStrings, ReadStringPairs x2, RefillStringPairs)
      and WriteStringPairs/TryWriteStringPair in NinoDictionary, plus 3 generated loops per polymorphic base
      (WriteElements, __WritePairs, __WritePairsThroughDispatch).
    • The element-kind decision is re-taken per site (§3 lists them): RawFormatter.Is< in 13 files, slots
      (SlotStride/NinoSlots) in 8, typeof(StringFormatter) in 3 (10 tests), typeof(DateTimeOffsetFormatter) 4 tests
      in NinoElements, INinoElementsFormatter/INinoPairsFormatter casts in 2, and the formatter binding table picks
      dedicated formatters per kind (UnmanagedArrayFormatter, NullableArrayFormatter, the raw and nullable
      ListFormatters).
    • Storage reached in place: List (ListAccess), Queue ring (two spans), Stack array, HashSet/Dictionary
      entries (only when no entry is free: CollectionFields.Entries returns null when count != bound), SortedList
      arrays (int and same-type integer keys only), PriorityQueue heap (<int,int> only), Collection<T>'s list,
      multi-dim arrays, ImmutableArray (value types only: references take a foreach).
    • Strided gathers exist once already: NinoBlockCollections.WriteAll<TEntry, TProjection> over SetEntryBlock<T>,
      SetEntryBytes<T>, MapEntryBlock<TKey,TValue>: the block plan's permute kernels with a map shifted by the value's
      offset in the entry. This is the gather the design generalizes.
    • Netstandard2.1 (Unity, IL2CPP, Mono): block values go through NinoBlockPlan.Formatter.WriteFixed (a boxed
      interface, one interface call per element where no Burst kernel runs), slots through NinoSlots.Formatter (same),
      polymorphic element loops through Traits.Elements (boxed, one interface call per collection), and no pair loop at
      all (#if NET8_0_OR_GREATER in Nino.Core and in the generated code).

    2. The abstraction

    2.1 A cursor and a layout

    A view of storage is a sequence of segments. A segment is a cursor: a ref TEntry to its first entry and a
    count. How an element lies in an entry is the layout, a stateless struct type argument whose members are all
    JIT-time constants:

    // Nino.Core/Internal/Collections/Storage/NinoLayouts.cs (new)
    internal interface INinoLayout<TEntry, T>
    {
        /// ref to the element inside an entry (the entry itself for dense storage; entry.Value; entry.Key; tuple.Item1).
        ref T Element(ref TEntry entry);
    
        /// Byte offset of the element in the entry (0 for dense). A constant: Unsafe.ByteOffset of a default entry,
        /// cached in a static readonly field of the layout (NinoBlocks.Offset does this today).
        int Offset { get; }
    
        /// Whether every entry of a segment is in use: true for arrays, rings, heaps; false for Dictionary and HashSet
        /// entries walked up to their bound (then InUse is asked per entry).
        bool Dense { get; }
    
        /// For !Dense only: entry.Next >= -1 (the free-list encoding of the runtime, proven at startup, §10).
        bool InUse(ref TEntry entry);
    }
    
    internal struct Same<T> : INinoLayout<T, T> { ... }                                  // arrays, lists, rings, stacks
    internal struct SetValue<T> : INinoLayout<CollectionFields.SetEntry<T>, T> { ... }   // HashSet entries
    internal struct MapKey<K, V> : INinoLayout<NinoDictionaryEntry<K, V>, K> { ... }     // Dictionary keys
    internal struct MapValue<K, V> : INinoLayout<NinoDictionaryEntry<K, V>, V> { ... }   // Dictionary values
    internal struct Item1<A, B> / Item2<A, B> : INinoLayout<(A, B), A|B> { ... }         // PriorityQueue heap nodes

    The stride is Unsafe.SizeOf<TEntry>(), a constant. What the vector kernels need is all here: the start
    (ref Unsafe.As<TEntry, byte>(ref first) + Offset), the count, the stride, and contiguity (Dense && SizeOf<TEntry> == SizeOf<T> means a plain span; anything else is strided).

    A segment cannot be a field of a struct passed as a generic argument (no ref fields outside ref structs, and
    netstandard2.1 has no allows ref struct), so segments are passed as (ref TEntry first, int count) and a view of two
    segments (a wrapped ring) is two calls of the same loop on the same writer. Nothing is lost: the second call starts at
    the array's start and computes its own alignment (§4.3).

    2.2 Views per collection

    collection segments layout notes
    T[], Span, Memory, ArraySegment, ImmutableArray, T[,].. 1 Same<T> multi-dim: row-major, one segment
    List<T>, Collection<T>/ObservableCollection<T> (wrapped list) 1 Same<T> ListAccess.AsSpan, CollectionFields.List
    Queue<T> 1 or 2 (wrapped) Same<T> head..end, then 0..tail
    Stack<T> 1 Same<T> bottom to top (the wire order)
    HashSet<T> 1 (entries 0..bound) SetValue<T> Dense when count == bound, else in-use test
    Dictionary<K,V> 1 MapKey + MapValue pair loops take two layouts over one cursor
    SortedList<K,V> keys 1 + values 1 Same<K>, Same<V> pair loops take two cursors in lockstep
    PriorityQueue<E,P> 1 (nodes 0..size) Item1, Item2 heap order is the wire order
    ConcurrentQueue<T> (and BlockingCollection over it) per segment's slots QueueSlot<T> optional, §7.3
    ReadOnlySequence<T>/ReadOnlySequence<byte> one per segment Same<T> §7.2
    LinkedList, SortedSet, immutable trees, IEnumerable gathered runs Same<T> over a rented span §7.2

    2.3 Pairs

    A pair loop is one loop over two element streams advanced in lockstep: (ref TKeyEntry k, TKeyLayout) and
    (ref TValueEntry v, TValueLayout). A Dictionary passes the same ref entries[0] for both with MapKey/MapValue;
    a SortedList passes ref keys[0] and ref values[0] with Same<K>/Same<V>; a PriorityQueue passes the node
    array twice with Item1/Item2. The JIT sees two refs to the same address for a dictionary and keeps one register
    (checked in the listing; if it does not, a Same<TEntry>-cursor overload for the shared case is the fallback).

    2.4 Reads fill storage through the same view

    A read targets one of three kinds of storage, all expressed as a view:

    1. Existing storage of the right size (an array of the length, an existing list's items, an empty queue's ring
      from 0): one dense segment, the element loop reads into it (NinoElements.Read today; NinoCollectionViews.ReadInto
      already does this for Queue and Stack).
    2. New storage (a new array, a list made over a new array, a SortedList's two arrays, a PriorityQueue's node
      array): allocated by the size rules that exist (MinWireSize, Heavy, Capacity, NewOrSame/Publish for
      uninitialized arrays), filled through a dense segment, then published (count, version, head, tail).
    3. Hashed fill: a new plain HashSet/Dictionary (default or seeded comparer) sized for the count. Its entries
      array is a strided segment (SetValue, MapKey/MapValue): the element loop reads the keys and values straight
      into the entries, then HashTables.Build hashes them and links the buckets in one pass, counting collisions
      against MaxHashCollisions and rejecting duplicates exactly as HashTables.Fill does for raw keys today
      (Read dictionaries of polymorphic values as fast as LuminPack: fill entries, then buckets #320's "fill entries, then buckets" generalized from raw keys to every kind). Where HashTables.Plan says the BCL
      guards the table itself (strings on .NET: the dictionary switches to randomized hashing after 100 collisions), the
      read keeps adding through the dictionary, so no rule moves out of the BCL.

    For the hashed fill of a fixed kind (raw, block, slot), the read is a scatter: a block of wire bytes into strided
    entries. Raw and block values take NinoBlockCollections.ReadAll with the projected map (the read twin of the
    MapEntryBlock gather); slots read into a rented dense run of at most 256 elements through the slot kernel, then
    move into the entries (§4.1).


    3. One decision per element type

    3.1 NinoKind<T, TFormatter>

    One class, generic over the element and its formatter only, decides once:

    internal static class NinoKind<T, TFormatter> where TFormatter : struct, INinoFormatter<T>
    {
        // The order the owner set (#355). Every test is on typeof and on other static readonly fields, never on
        // default(TFormatter) is I (IL2CPP and Mono box that test), so the netstandard build reads it once, no box.
        public static readonly Kind Value =
            RawFormatter.Is<T, TFormatter>()                               ? Kind.Raw    // unmanaged / raw: one block
          : NinoSlots<T, TFormatter>.Stride > 0                            ? Kind.Slot   // T? of raw T, NinoNullable<T>
          : NinoBlockPlan<T, TFormatter>.Size > 0                          ? Kind.Block  // block formatter (composed, DTO)
          : Implements(typeof(INinoStringFormatter))                       ? Kind.String // String, Utf8String (#347)
          : !typeof(T).IsValueType && Implements(typeof(INinoDispatches))  ? Kind.Polymorphic
          :                                                                  Kind.General;
    
        public static readonly int Stride   = ...;  // wire bytes per element for Raw/Slot/Block, else -1
        public static readonly int MinWire  = ...;  // what MinWireSize/MinHashedSize/MinSingleSize compute today
        public static readonly bool Overwrites, CopiedWhole, WritesOnLocal, Heavy, HeavyHashed;   // today's Traits
        public static readonly int PrefetchThreshold = NinoPrefetch.Of<TFormatter>.Threshold;     // int.MaxValue = off
    }

    On .NET 8+ Tier1 folds every static readonly of an initialized class, so switch (NinoKind<T,TF>.Value) leaves one
    arm in the listing. For value types the existing intrinsic tests (RawFormatter.Is, IsReferenceOrContainsReferences)
    stay in front, as NinoElements already does, so shared code over a class T never loads the field (one runtime
    lookup otherwise): the accessor is IsReferenceOrContainsReferences<T>() ? (classes: Polymorphic or General or String) : NinoKind.Value. On netstandard the field is one load per collection, never per element.

    3.2 Where the decision is repeated today (each copy goes)

    site what it decides goes in
    NinoElements.Write/Read/WriteBlock/BlockStride/ReadOverwrites/CopiedWhole/MinWireSize/MinHashedSize/MinSingleSize, Traits<T,TF>, NinoSlots<T,TF>.FixedStride raw / DTO / slot / block / string / elements / general PR 1 (traits), PR 3 (loops)
    NinoDictionary.Write (raw+raw, raw+string, string+raw, INinoPairsFormatter, general), Read (raw+raw, raw+string, string+string, general), Refill (raw+string) pair kinds PR 3, PR 5, PR 6
    HashSetFormatter.Serialize (raw entries, slots, WritesOnLocal, enumerator), Deserialize (raw fill, slots, plan, general) element kind for sets PR 3, PR 6
    QueueFormatter, StackFormatter, CollectionFormatter, ConcurrentStackFormatter, ProducerConsumerFormatter (BlockStride, SlotStride, ReadOne) block vs one-by-one PR 3
    BclCollections (LinkedList raw ring / slots / each; SortedSet packed tree), BclDictionaries (SortedList TypeCode switch, <int,int>, SortedDictionary <= 8 byte gate) raw and int special cases PR 3, PR 6
    PriorityQueueFormatter + PriorityQueueHeap (intPair, TryAdopt(PriorityQueue<int,int>)) int only PR 6
    KeyValuePairFormatter, TupleFormatters.g.cs (26 RawFormatter.Is) block only when every item raw PR 2
    Nino.Immutable: ImmutableArrayFormatter (!typeof(T).IsValueType -> foreach), ImmutableCollections, HashSet/Dictionary/Queue/Stack formatters references by hand PR 3, PR 7
    Reader.Strings.cs ReadStrings, ReadStringPairs x2, RefillStringPairs; NinoDictionary.WriteStringPairs typeof(StringFormatter) PR 5
    NinoElements.Write default(TFormatter) is INinoElementsFormatter<T>; NinoDictionary.Write is INinoPairsFormatter polymorphic PR 1, PR 4
    generated: DispatchEmitter.EmitWriteElements (span only), __WritePairs (dictionary only), FormatterTraitsOf name table (Flat, PreservesReadContext) polymorphic loops per container PR 4 (loops); the name table is #F9, out of this series
    binding: BuiltInFormatters/NinoFormatterResolver pick UnmanagedArrayFormatter, NullableArrayFormatter, raw/nullable ListFormatters dedicated formatters per kind PR 3: kept only where they do something the shared path cannot (the top-level raw array's INinoRawArrayFormatter entry, external writes), else bound to the general array/list formatter

    4. The per-element-kind loops

    All loops live in one file pair, Internal/Collections/Traversal/NinoElements.cs (writes) and NinoElements.Read.cs
    (reads), generic over <TEntry, TLayout, T, TFormatter>. The collection formatters call only
    NinoElements.Write(ref first, count, ref writer) / Read(...) per segment and NinoPairs.Write/Read(...) for pairs.
    Every loop below exists once; a Same<T> layout makes it the span loop of today, so arrays and lists keep their code.

    4.1 Fixed kinds (Raw, Block, Slot): one reservation, the SIMD kernels

    Write (one capacity check per segment: writer.ReserveElements(count, Stride) or one ReserveCounted for a whole
    ring, as QueueFormatter does now):

    kind dense segment strided segment (entries)
    Raw NinoLayout<T>.CopyToWire (a NinoUnsafe.Copy block copy, padding masks; AMD downward copy when the gap mod 4 KB < 2 KB, #326) NinoBlockCollections.WriteAll<TEntry, Projected<TEntry,TLayout,T,RawBlock<T>>>: the AVX-512 group permutes / 16-byte lanes / Arm64 tbl gather the value out of each entry (exists for SetEntryBlock, MapEntryBlock)
    Block (incl. DateTimeOffset, composed tuples and pairs after PR 2) NinoBlockCollections.WriteAll<T,TF> (Groups, Lanes, Permute64; Burst kernels via NinoKernels on netstandard) same call with Projected<...>: the map is NinoBlockMap.Block<T,TF> shifted by TLayout.Offset (the merge NinoBlockMap.Block does for nested structs today)
    Slot NinoNullables<T> kernels (WriteSlots, lined stores, CopyRealigned) where SlotsWriteInPlace: gather the raw values as bytes (SetEntryBytes today) into the reservation, then the slot kernel in place (1,000 int?: 227 ns against 1,140 copied, local, HashSetFormatter.WriteSlots); otherwise a rented dense copy of at most 256

    Read (one TakeElements per segment, prechecked where the length check already proved the bytes):

    kind dense strided (hashed fill)
    Raw NinoUnsafe.CopyToNew (Arm64 short copy) or NinoChecks.Values + copy for bools/Untrusted ReadAll with the projected raw map (scatter)
    Block NinoBlockCollections.ReadAll (aligned loads where measured: Ice Lake Groups.Aligned) ReadAll with the projected map
    Slot NinoNullables.ReadPrechecked slot kernel into a rented dense run of <= 256, then a block move into the entries

    Which kernels run directly over a strided view: every NinoBlockCollections kernel (they already take a source map with
    offsets per field and a source stride, size), so raw and block values gather and scatter at full width; the plain
    copy (NinoUnsafe.Copy) and the slot kernels (NinoNullables, NinoMask.CopyLanes) assume a dense source and need the
    two-step form above (gather as bytes, then the kernel in place; or kernel into a dense run, then scatter). A dense
    segment always takes the copy or slot kernel itself.

    In-use gaps (free entries) for fixed kinds: the loop scans InUse for the next run of in-use entries (a vector compare
    of the Next fields where the stride allows, else scalar) and calls the gather per run, so the kernels never see a
    free entry. Runs shorter than a vector go element by element through WriteFixed (a constrained call, §5).

    4.2 Strings (Kind.String, #347)

    One cursor loop over the view for StringFormatter and Utf8StringFormatter (an encoding type argument, the
    [NinoUtf8] form), writing with the FreeSpace/Commit pair (WriteStringPairs' technique: the cursor ref byte dst, nuint pos, nuint end in registers, falling back to growing the buffer only when the longest form of a string
    does not fit), and reading with Reader.ReadStrings' register cursor. Pairs: the same cursor with the other item a
    fixed-kind value written at constant offsets (raw key + string, string key + raw value, string + string), so the 2x2
    matrix of hand-written loops becomes one loop instantiated per pair of kinds. Untrusted checks per pair stay
    (NullKey, hash flooding through §2.4).

    4.3 Polymorphic (Kind.Polymorphic): the generated loop, dispatch inline

    Nino.Core calls the base's generated loop through a constrained call on the formatter (§5), per segment:

    default(TFormatter).WriteElements<TEntry, TLayout>(ref first, count, ref writer);            // sets, lists, rings
    default(TValueFormatter).WritePairs<TKE, TKL, TKey, TKeyFormatter, TVE, TVL>(ref k, ref v, count, ref writer);

    The generated methods (DispatchEmitter.EmitWriteElements) are the branch's WritePairs<TKey, TKeyFormatter>
    generalized over the layout: the chain of exact type checks inline, the writer in a local, IsDeep once, the deep and
    unknown-subtype paths out of line, the in-use test inlined (a constant true for dense layouts, so arrays compile to
    today's loop). The span overload WriteElements(ReadOnlySpan<T>) is gone: a span is Same<T> over its reference.
    Reads stay in Nino.Core's general loop (__ReadSubtype inlined through the base formatter's Deserialize): a
    hand-written exact read loop was not faster (dispatch.md, #308: 12 pairs 322 against 321 ns); the read's gain is the
    hashed fill (§2.4).

    4.4 General (Kind.General)

    default(TFormatter).Serialize(TLayout.Element(ref e), ref local) with the WritesOnLocal choice (value types and flat
    sealed classes on a local writer out of line; others on the caller's writer, measured: SelfTree 0.86x otherwise), and
    ReadEach out of line with the reader by value. Same code as today's NinoElements loops, now over a layout.

    4.5 Alignment (every loop)

    The view carries no alignment field: the address is the information. Each kernel computes its own head from the
    addresses it is given, once per segment:

    • Writes align their stores to the reservation (the writer's destination): NinoUnsafe.BytesToAligned(ref dst, width) for slot kernels and copies, Lanes512.CopyRealigned where whole elements never land on a line (4-byte
      length then 8-byte values), as the nullable kernels do. Strided gathers load wherever the entries lie (strides of
      12, 16, 24 bytes), and store aligned vectors; the group permutes already write whole 64-byte vectors.
    • Reads into storage align their stores to the destination storage (the array or entries), except where aligned
      loads measured better (NinoBlockCollections.Groups on Ice Lake: the source aligned, NinoBlockPlan.Aligned).
      Dense raw reads stay on CopyToNew (aligned destination, rep movsb where FSRM wins, vectors elsewhere).
    • Copies on AMD go through NinoUnsafe.Aliases/CopyVectorsDown (perf(core): copy downward on AMD where a forward copy hits 4K aliasing #326): the gap between source and destination mod
      4 KB under 2,048 bytes copies downward. Since the second segment of a ring starts at the array's start, its gap
      differs from the first's: each segment is its own call, so each gets its own test.
    • Measurement: every kernel PR runs the phase controls of vectors-nullable.md (source pinned at one phase per
      process, destination at offsets 0 and 1 of the buffer) and BlockCopyTests' distance classes; a harness whose source
      and destination share their low 12 bits is not evidence (vectors-nullable.md: it ranked the aligned form 30 % wrong).

    4.6 Prefetch for class elements (every collection kind)

    Today only top-level arrays and lists prefetch (NinoDirect.*Prefetched, NinoPrefetch.Write/Read), and a test in the
    shared element loops was measured at 2-7 % on short nested lists (CommonTypes Orders, Tree). The design keeps that
    cost at zero where prefetch is off and moves the gate into the class kinds (Polymorphic, General with T a class,
    and dictionary values):

    • Gate, the same as today: count > NinoKind<T,TF>.PrefetchThreshold (a quarter of the last-level cache over the
      element's PrefetchBytes, at least 1,024; int.MaxValue for a formatter that is no INinoPrefetchFormatter /
      INinoObjectPrefetchFormatter, i.e. every project built without NinoPrefetchLargeCollections), then the 17-object
      allocation-order sample (NinoPrefetch.Scattered, both directions where ReverseReadIsLocal). Tier1 folds the
      threshold, so in a project without the property the test is count > int.MaxValue and vanishes; the netstandard
      build compiles it out (NinoPrefetch.Supported is false there: no prefetcht0, no scalar Arm64 prefetch).
    • Loop: past the gate, out of line, the segment is walked in runs of NinoPrefetch.Run (16): before each run
      Ahead<TFormatter> prefetches the objects two runs ahead and the members of the next run. Ahead and Scattered
      gain a byte stride (nint stride = SizeOf<TEntry>, the element at TLayout.Offset): a dictionary's values are
      every 24th byte, a set's every 16th; dense layouts pass sizeof(object) and compile to today's code.
    • Polymorphic and pair loops: Nino.Core calls the generated loop once per run of 16 after Ahead (the generated
      loop is unchanged; a call and a writer copy in and out per 16 elements, which only long scattered collections pay).
    • Reads prefetch the existing objects read into (refills of lists, arrays, dictionary values on Refill); a fresh
      read has nothing to prefetch (the sample sees nulls and declines, as now).
    • Measured by: the existing prefetch benchmark cases (1,000,000 scattered and ordered objects, offsets 0 and 1)
      extended to HashSet<Class>, Dictionary<int, Class>, Dictionary<int, Base>, Queue<Class> wrapped,
      ImmutableArray<Class>; the off control (a gate no input passes) and the property off; CommonTypes Orders and Tree
      with the property on (the 2-7 % that kept nested loops out before); x64 and Arm64 runners per CPU.

    5. Reaching formatter capabilities

    5.1 The contract: constrained calls on TFormatter, never casts

    The branch claude/dictionary-pairs-general proved the form on .NET 10: a generic default interface method on
    INinoFormatter<T>, overridden by the generated struct, called as default(TValueFormatter).WritePairs<TKey, TKeyFormatter>(...), is a direct call (value-type key), or one generic-dictionary load per call from shared code over
    a class key, never per pair; no box, no CORINFO_HELP_VIRTUAL_FUNC_PTR (dispatch.md on the branch). A cast
    (((I)default(TF)).M<T>()) boxes and goes through VIRTUAL_FUNC_PTR (35 / 49 / 94 / 215 / 693 ns at 1-100 pairs
    against 15 / 23 / 40 / 81 / 240).

    Generalized, INinoFormatter<T> carries a small set of default methods, in every build (netstandard2.1 included):

    public interface INinoFormatter<T>
    {
        void Serialize(T value, ref Writer writer);
        void Deserialize(ref Reader reader, ref T value);
    
        // [EditorBrowsable(Never)]; defaults are the general loops; called only where NinoKind says the formatter overrides
        void WriteElements<TEntry, TLayout>(ref TEntry first, int count, ref Writer writer)
            where TLayout : struct, INinoLayout<TEntry, T>;
        void WritePairs<TKE, TKL, TKey, TKeyFormatter, TVE, TVL>(ref TKE keys, ref TVE values, int count, ref Writer w)
            where ...;
        void WriteFixedValue(in T value, ref byte destination);   // block and slot formatters: their WriteFixed
        void ReadFixedValue(ref T value, ref byte source);        // block formatters: their ReadBlock
    }
    • Polymorphic bases (generated) override WriteElements/WritePairs with the dispatch loops.
    • Block formatters (generated structs, KeyValuePairFormatter, tuples, DateTimeOffsetFormatter, the projections)
      override WriteFixedValue/ReadFixedValue with a forward to their WriteFixed/ReadBlock. NinoBlockCollections'
      per-element fallback then calls default(TFormatter).WriteFixedValue(...): a direct call on netstandard too, where
      today it is NinoBlockPlan.Formatter.WriteFixed through a boxed interface per element. The loop stays in Nino.Core
      (the owner declined putting the loop in each formatter, dispatch.md inventory (3)); the formatter carries a one-line
      forward. INinoBlockFormatter<T> keeps its members (public, the generator emits them); only the call site changes.
    • Slot formatters (internal, Nino.Core's own) are reached by NinoKind.Value == Kind.Slot and then by Unsafe.As of
      nothing: they are Nino.Core's own structs, so the slot loop names them as type arguments of an internal generic
      (NinoNullables<T>.WriteSlots for T?, NinoNullable<T>), selected by typeof(TFormatter) == typeof(UnmanagedNullableFormatter<...>) folded inside NinoKind, not per site.
    • A default method is never called on a formatter that does not override it: on CoreCLR and IL2CPP a default method
      called through a constrained call on a struct boxes this. NinoKind decides "overrides" by reflection once
      (typeof(TFormatter).GetInterfaceMap(typeof(INinoFormatter<T>)) targets declared on the struct, or a marker
      interface: INinoDispatches for polymorphic bases, INinoBlockFormatter<T> assignability for fixed values), never
      by default(TFormatter) is I.

    5.2 static readonly traits on netstandard2.1 (IL2CPP, Mono)

    IL2CPP and Mono box default(TFormatter) at each is test and each cast (a GC allocation each time: the reason
    Traits.Elements and NinoSlots.Formatter exist). Every test therefore moves into NinoKind<T, TFormatter> (and
    NinoBlockPlan, NinoPrefetch.Of), classes generic over the formatter (and the element), whose static initializers run
    typeof tests once. On .NET 8+ Tier1 they are constants; under NativeAOT, IL2CPP and Mono they are one load each per
    collection. No static readonly I Formatter = default(TF) as I survives: every per-element call becomes a constrained
    call (§5.1).

    5.3 Default interface methods and IL2CPP

    • C# 8 default interface methods compile for netstandard2.1 (the target that added runtime support for them) and run
      on Mono and IL2CPP from Unity 2020.2; the package requires 2022.3 (dispatch.md on the branch). Unity's docs do not
      list them among IL2CPP's limitations (IL2CPP limitations).
    • IL2CPP never shares code for value-type instantiations ("IL2CPP does not share generic method implementations when
      T is a value type because the size of each value type will differ", generic sharing). Every formatter is a
      struct type argument, so a method like NinoElements.Write<Foo, FooFormatter> is compiled for exactly that pair, and
      a constrained call on FooFormatter inside it is resolved at conversion time to FooFormatter's own method: a
      direct C++ call, with the struct passed by pointer (no box). This is the same reason default(TFormatter).Serialize
      is direct on IL2CPP today.
    • The risk is generic virtual methods (WriteElements<TEntry, TLayout>, WritePairs<...>): IL2CPP lists "some calls
      to generic virtual functions that can't be inferred at compile time" as a case it compiles to fully shared fallback
      code, "slower because it can't determine a type's size, or whether it's a reference or value type"
      (IL2CPP limitations; the Full Generic Sharing post u-fgs describes the same fallback). A constrained
      call on an exact struct with exact method arguments is inferable, so it should be direct; a call from code IL2CPP
      itself shares (the "Optimize for code size and build time" setting, or a formatter generic over a class under full
      sharing) is the case that may reach il2cpp_codegen_get_generic_virtual_method. Unity fixed a bug where IL2CPP boxed
      values on generic virtual calls on structs in 2019.3.13f1 (issue). No source states the codegen for a
      constrained generic DIM call directly, so PR 1 reads the C++ of unity.yml's player build for every new call site
      (grep il2cpp_codegen_get_generic_virtual_method|Box\(|VirtualActionInvoker|InterfaceActionInvoker in the
      generated Nino.Core.cpp and the test assembly's cpp) before anything depends on it.
    • Fallback if IL2CPP does not resolve them: the element loop takes a non-generic strided form on netstandard
      (WriteElements(ref T first, int count, nint stride, nint inUseOffset, ref Writer); references only, so T is the
      base) and the pair loop stays Nino.Core's shared loop there. Fixed kinds do not depend on generic virtual methods at
      all (WriteFixedValue is not generic).

    5.4 Partial types

    The generator already requires partial for private members on Unity and emits members into users' types.

    • A generated static member on the user's type removes nothing: the generated formatter struct is already named
      directly by every call site (direct calls, inlined), and a static on the type is the same call with a different
      owner. Its only value is private access, which is already used.
    • A generated virtual member (LuminPack's form: the base declares __Write(ref Writer), each subtype overrides it)
      replaces the chain with one indirect call per element. Measured in Nino with real bodies (dispatch.md, 13b9a7b,
      LuminPack's 20-subtype list, bytes identical): chain 4.93 µs fixed order / 4.84 shuffled, virtual 5.15 / 6.95. It is
      an indirect call per element, which the owner's rule excludes, and IL2CPP has no PGO to guard it
      (VirtualActionInvoker per element).
    • Where partial could still help: the cold fallback for a subtype the chain does not know (another assembly, a
      HybridCLR hot-update type): today a registry lookup by type id, then a handler call. A virtual on a partial base
      would make that one indirect call without the lookup, but only for subtypes compiled with the generator and declared
      partial; the hot path does not change. Not proposed: the gain is on a cold path and it adds a requirement on users.
    • Static abstract interface members (C# 11) would let INinoLayout/kinds be static, but need .NET 7+; netstandard2.1
      and Unity cannot use them. The stateless-struct-instance form (default(TLayout).Element(ref e)) is what works on
      both and inlines to the same code.

    6. Polymorphic dispatch per element

    Requirement: no virtual or indirect call per element on either target; choose by measurement.

    6.1 Numbers that exist (local x64, LuminPack's List<IFoo>, 1,000 values, 20 subtypes; per element = µs / 1,000)

    form fixed order shuffled source
    chain of exact type checks inline in the loop (today) 4.93 ns (3.7-3.9 after e178937) 4.84 ns dispatch.md 13b9a7b, #305
    virtual method generated into partial classes (LuminPack's) 5.15 ns 6.95 ns dispatch.md 13b9a7b
    jump table through a hash of the method table 6.4 ns 16.0 ns dispatch.md (#305)
    table of delegates by method-table hash 5.0-5.7 ns - dispatch.md (98518d3)
    chain called per element (dispatch not inlined, writer by ref) 4.9-5.05 ns - dispatch.md
    LuminPack itself 4.40 ns - dispatch.md

    value.GetType() == typeof(S) already compiles to a compare of the object's method-table pointer with a constant
    (no call): "comparing method-table pointers" is what the chain is. The first subtype against only the 19th (3.9 against
    6.9 µs) was the 19th's larger body, not its place.

    6.2 New local probe (this design; tiny bodies: id + two ints; Xeon 2.1 GHz, .NET 10; ns per element)

    Probe: scratchpad/dispatchprobe/Program.cs, 1,000 elements, best of 30 x 200 after warm-up. Tiny bodies exaggerate
    the dispatch's share; with real bodies the chain led (6.1).

    order chain virtual (PGO on) MRU type + switch (PGO on) chain (PGO off) virtual (PGO off) MRU (PGO off)
    random 7.49 6.05 5.76 5.07 4.30 6.92
    cyclic declaration order 4.22 3.08 5.82 4.88 2.95 6.89
    sorted runs (50 of each) 4.65 3.68 4.01 4.66 3.69 4.58
    one type, first in chain 2.13 2.63 3.24 2.68 2.54 3.60
    one type, last in chain 5.28 2.62 3.92 5.44 2.53 3.58

    What it says (local, guidance only): with bodies this small the chain's position cost shows (about 0.17 ns per
    compare: first 2.1-2.7 against last 5.3-5.4), the virtual call is cheap where it predicts, and caching the last type
    only helps when runs are long and the type sits deep in the chain; its switch is an indirect jump (a jump table),
    which mispredicts on mixed input (6.9 ns PGO off, random). The same random/fixed spread with real bodies inverted the
    ranking (6.1). So:

    6.3 Choice and what to measure on runners

    • Keep the chain (no indirect call or jump per element on any target; the only form that meets the rule on IL2CPP,
      where a virtual is a VirtualActionInvoker with no PGO and a jump table is an indirect jump).
    • Order: declaration order today. Two orders can be generated without run-time state: (a) by body size ascending
      (small bodies first, since a large body's compare cost is relatively small), (b) a user hint ([NinoType]
      subtype order or a frequency attribute: public API, owner's call). Frequency at run time cannot reorder a compiled
      chain without an indirect jump.
    • Caching the last type: jumping straight to the last type's body needs an indirect jump (the probe's switch), which
      the rule excludes and which lost on mixed input. The only form without one is a loop specialized per subtype, chosen
      once per collection by its first element's type and falling back to the chain at the first mismatch: one copy of the
      loop per subtype (code size x20). Worth it only if runners show long runs of one type in real data. An experiment,
      not a default.
    • Runner probe (PR 4): a DispatchTest benchmark class with LuminPack's 20 bodies, List<IFoo> / HashSet<IFoo>
      / Dictionary<int, IFoo> of 1,000 in random, cyclic and sorted-run orders, rows: chain in declaration order, chain
      by body size, per-type specialized loop with chain fallback, virtual on partial (LuminPack, as the control), and
      LuminPack itself; x64 and Arm64 runners per CPU; plus the IL2CPP C++ of the chain (no Invoker per element) and the
      Unity benchmark (Run the C# benchmark models and kernel cases in the Unity IL2CPP benchmark #340). Decision rule: the chain stays unless a form without an indirect call wins on every CPU beyond
      the floor.

    7. Every collection on the view

    7.1 Contiguous storage (all through NinoElements/NinoPairs per segment)

    • T[], Span, Memory, ArraySegment, ImmutableArray (references too: F6's foreach goes; strings must stay on
      par with 264 ns / 100, the reason it was there, so the call is the inlined span path, not ArrayFormatter out of
      line), multi-dim (one segment; MultiDim keeps the shape header).
    • List<T>, Collection<T>, ObservableCollection<T> (writes any subclass, reads the exact type: subclasses may
      override InsertItem), ReadOnlyCollection over a list or an array.
    • Queue<T>: one or two segments; reads into the ring from 0 (ReadInto).
    • Stack<T>: the array bottom to top; ConcurrentStack keeps its node walk (§7.2).
    • HashSet<T>: entries walked for every T (F5), free entries by the in-use test instead of the enumerator; reads: the
      hashed fill for every kind HashTables plans (§2.4).
    • Dictionary<K,V>: pairs over one cursor and two layouts, for every key and value kind; free entries by the in-use
      test; reads: hashed fill (Read dictionaries of polymorphic values as fast as LuminPack: fill entries, then buckets #320), refill unchanged in its rules (merge by key), its string loop folded into PR 5.
    • SortedList<K,V>: two cursors; reads: keys and values scattered into two new arrays straight from the pair block
      (block plan per side, the int Interleave/Deinterleave kernels kept as the kernels of 4-byte lanes), then the
      order check through Comparer<K>.Default (a vector kernel where K is a signed integer), adopted when in order and
      no custom comparer, else added (Extend the int-only SortedList and PriorityQueue paths to every raw pair #350).
    • PriorityQueue<E,P>: the node array as two layouts; reads: nodes filled, heap property checked generically
      (Comparer<P>.Default; the int four-children vector check kept for 4-byte signed priorities), adopted, else enqueued
      (Extend the int-only SortedList and PriorityQueue paths to every raw pair #350).
    • Concurrent: ConcurrentQueue<T> segments hold Slot { T Item; int SequenceNumber } arrays, a strided view with an
      in-use test by sequence number; the snapshot (ToArray) is the measured cost today (4,200 against 3,760 ns per
      1,000 int?). Optional (§11): concurrency rules make the in-place walk a version-checked snapshot at best.
    • Immutable: ImmutableArray (above). ImmutableList, ImmutableHashSet/Dictionary, sorted ones are trees (§7.2).

    7.2 Non-contiguous collections, segment by segment

    Each is fed to the same per-kind loops as dense segments; how each is fastest:

    • ReadOnlySequence<T> (and ReadOnlySequence<byte>): each ReadOnlyMemory<T> segment is a dense span: one call
      of the loop per segment, the length written once before (the wire has one count). Fastest because each segment is a
      plain span: raw/block segments get the copy and block kernels unchanged; nothing is copied. Short segments (under a
      vector) are not merged: the kernel's scalar tail handles them.
    • LinkedList<T>: a ring of nodes (CollectionFields.LinkedNode). Fixed kinds: walk the ring writing each value
      straight into the one reservation (WriteLinkedRing today, pairs of nodes at >= 32: jit-collections.md); a gather
      into a rented span then the kernel adds a pass over memory, so for raw values the walk is fastest; for slots, the
      walk writes the raw values as bytes into the reservation and runs the slot kernel in place (as HashSet slots).
      Class kinds: gather the references into a rented span of at most Run x k (e.g. 256) and run the dense loop over it
      (the polymorphic generated loop and prefetch need a span; a node walk would keep the loop out of the generated
      dispatch). Reads: build the ring with ReadLinked (one node per element, unchanged), values read by the kind loop
      into a rented dense run first for fixed kinds.
    • SortedSet<T> and SortedDictionary: the red-black tree in order. Raw values already take the packed tree
      writer (SortedSetNodes, TryWritePackedTree); the <= 8 byte gate of SortedDictionary (F7) is aligned with
      SortedSet's rule (any raw unpadded type) once its reason is found. Other kinds: an in-order walk gathering into
      rented runs of 256, then the dense loop per run (one Ahead gate per run for classes). Reads: SortedSetTrees builds
      the tree in one pass from a sorted dense run (exists), the run read by the kind loop.
    • Immutable trees (ImmutableList, ImmutableHashSet/Dictionary, ImmutableSortedSet/Dictionary): walk the
      nodes (Nino.Immutable's HashTrees/SortedTrees mirrors) gathering into rented runs; reads build the tree from a
      dense run (exists for hash and sorted trees). ImmutableQueue/ImmutableStack: linked; same as LinkedList.
    • ConcurrentStack<T>: the captured node chain (ConcurrentStackNodes): counted, reserved once, walked bottom to
      top for raw values (exists); other kinds gathered into runs.
    • A plain IEnumerable<T> (no list, array or known collection behind it): buffered into a rented span (count
      known: ICollection<T>.CopyTo into a rented array, NinoCollections.RentCopied; unknown: grow a rented buffer),
      then the dense loop. The single extra pass costs less than an enumerator MoveNext interleaved with the kernels, and
      it is the only form that lets the polymorphic loop, the block kernels and prefetch run.

    Whether "gathered runs" or "node by node" is faster is measured per kind in the PR that moves each (§9, PR 7): the
    rule above is the expected outcome (fixed kinds walk into the reservation, class kinds gather), from the existing
    numbers (WriteLinkedRing pairs at >= 32, HashSetFormatter.WriteSlots gather-then-kernel 227 against 1,140 ns).


    8. LuminPack

    Cloned anonymously (TheLight-233/LuminPack 3cc4eac, scratchpad/luminpack-src/LuminPack).

    Collections. No runtime collection layer: the generator writes each member's collection code as text per type
    (CollectionEmitter.cs, 2,852 lines; ArrayEmitter, UnmanagedArrayEmitter, ImmutableCollectionEmitter, ...). For a
    Dictionary<K,V> member it emits a loop over LuminPackMarshal.GetDictionaryView(value)._entries (falling back to the
    enumerator for sparse dictionaries), writer.EnsureAdditionalCapacity(count * (sizeof K + sizeof V)) once for
    unmanaged pairs, and on read creates new Dictionary(length), reads keys and values straight into _entries[i], then
    TryRebuildFreshDictionaryBuckets builds the buckets in one pass with a collision count (falling back to Add when the
    layout is not the 64-bit one: it returns false on x86 and assumes the CoreCLR layout without a startup check). Lists go
    through LuminPackMarshal.GetListSpan/SetListSize, unmanaged blocks through Unsafe.CopyBlockUnaligned.
    LuminPackEvaluator can compute sizes ahead (a second pass).

    Polymorphism. LuminPackUnionDispatchCodeGenerator emits into the user's partial types an internal virtual __LuminPackUnionSerialize_X(ref LuminPackWriter) on the root and internal (sealed) override on each member with its
    id and body; closed generic members switch on a cached dispatch slot; types from other assemblies are found by method
    table in a registry (s_unionRegistry, delegate* entries).

    Why it is fast despite virtual members. The virtual call replaces what Nino used to pay per element (a call into a
    dispatch too large to inline, with the writer in memory: dispatch.md, #305); the rest is exact-type code: every
    collection loop is emitted for its exact types, so there is no shared generic code and no capability test, the writer's
    cursor stays in registers, unmanaged runs are one block copy, dictionaries walk their entries and fill fresh ones
    then build buckets. In Nino, the generated chain loop already beats its dispatch for lists and dictionary writes
    (dispatch.md: 3.7-3.9 against 4.4 µs; dictionary writes ahead at every size), and its read lead is the fresh-fill
    (#320).

    What fits Nino's constraints.

    • Fits: fill a fresh table's entries, then buckets in one pass, with the collision count (PR 6), behind Nino's startup
      layout checks and public-API fallback (stronger than LuminPack's x86 test). Exact-type specialization: Nino gets it
      from the JIT and IL2CPP's value-type instantiation of one generic loop instead of emitted text per member (DRY: one
      loop, not one per member type), the result in machine code being the same.
    • Does not fit: the virtual dispatch (measured slower in random order and an indirect call per element; §6); trusting
      the runtime's layout without a check (Nino reads hostile input and runs on Mono, IL2CPP, 32-bit); a size pre-pass
      (a second traversal of the object graph; Nino's reservation per block already removes per-element capacity checks);
      per-member emitted collection code (generated size and build time; Nino's generator benchmark tracks these).
    • Wire format: nothing in LuminPack's approach requires a format change.

    9. Migration plan

    Every PR lands on its own: tests (unit, runtime internals with a FastPaths row for each new layout, conformance and
    golden bytes unchanged, fuzz corpus), the machine code (python3 benchmarks/asm/asm.py compare origin/main: no method
    worse; the listings named per PR), a runner A/B per CPU (the benchmark skill: one A/B in flight, fewest lines), the
    Unity job's IL2CPP C++ where a call site changes, Unity DLLs refreshed where Nino.Core changes, and a docs(skills)
    commit (optimize, runtime-internals). The goal per PR is fewer loops in total; each lists what it deletes.

    PR 0 — land #345 (branch claude/dictionary-pairs-general). Already done on the branch: one generated
    WritePairs<TKey, TKeyFormatter> for every key (.NET 8+), deletes WritePairs32/64, WriteStringPairs (generated),
    WordKey<T>. Measure: as on the branch (asm.py on PolymorphicTest/GenericPolymorphicTest, the key-coverage tests,
    runner A/B against main and LuminPack). Closes #345 except netstandard (moved to PR 1).

    PR 1 — NinoKind and the capability contract (#346).

    • Add NinoKind<T,TFormatter> (§3.1) and the default methods on INinoFormatter<T> in every build (§5.1); generated
      polymorphic bases implement WriteElements/WritePairs in netstandard too (the #if NET8_0_OR_GREATER around the
      generated pair loop and in NinoDictionary.Write goes); block formatters forward WriteFixedValue/ReadFixedValue.
    • Deletes: default(TFormatter) is INinoElementsFormatter<T> and its cast, Traits.Elements (netstandard), the
      is INinoPairsFormatter gate's cast, NinoBlockPlan.Formatter as a call target (WriteValue/ReadValue become
      constrained calls), NinoSlots.Formatter as a call target, NinoElements.Traits (moved into NinoKind).
      INinoElementsFormatter<T> and INinoPairsFormatter are replaced by the default methods and one marker (owner's
      call, public).
    • Measure: Tier1 and NativeAOT listings, no CORINFO_HELP_ISINSTANCEOF*, box or indirect call per element; IL2CPP
      C++ of unity.yml: direct calls, no Box, no il2cpp_codegen_get_generic_virtual_method for the new sites (§5.3,
      with its fallback if they appear); Unity IL2CPP benchmark of block and slot collections before and after (Run the C# benchmark models and kernel cases in the Unity IL2CPP benchmark #340);
      .NET A/B of PolymorphicTest, dictionary cases, block-struct lists.

    PR 2 — fixed kinds compose (#348, #295).

    PR 3 — the storage view and the write loops over it (#349 F5/F6, #355 core).

    • INinoLayout and the layouts (§2.1); NinoElements.Write(ref first, count) per kind over a layout (§4); every
      contiguous collection's write calls it per segment (§7.1); free entries by the in-use test (startup-checked per
      runtime layout, §10).
    • Deletes: HashSetFormatter.WriteEnumerated/WriteSlots/WriteEach; NinoDictionary.WriteRaw/WriteEnumerated/ WritePairs (one NinoPairs.Write); QueueFormatter/StackFormatter/CollectionFormatter/ConcurrentStackFormatter
      /ProducerConsumerFormatter element-kind branches and WriteOne loops; BclDictionaries.WriteSortedListRaw/Scalar
      and the TypeCode split; PriorityQueueHeap.TryWrite's intPair case; ImmutableArrayFormatter's foreach;
      NinoElements.WriteOne (no per-element slot interface call left anywhere).
    • Measure: asm.py (array and list methods must be byte-for-byte or better: Same<T> makes them today's code);
      A/B of every collection kind of int, int?, string, a struct, a sealed class, a base, with dictionaries holding
      removed entries; IL2CPP code size (more instantiations: per layout) from the Unity build log.

    PR 4 — generated element and pair loops over the view (#349 F10, #345 remainder).

    • WriteElements<TEntry, TLayout> and WritePairs<TKE, TKL, TKey, TKeyFormatter, TVE, TVL> (§4.3) replace the span
      loop and the dictionary-only pair loop; sets, rings, ImmutableArray, SortedList and PriorityQueue values of a
      base get the inline dispatch.
    • Deletes: WriteElements(ReadOnlySpan<T>), __WritePairsThroughDispatch (free entries are in-use tests now; the
      deep path stays), the enumerator path in generated code.
    • Dispatch order: the §6.3 runner probe; the chain stays unless a form without an indirect call wins everywhere.
    • Measure: asm.py on PolymorphicTest/GenericPolymorphicTest; A/B against main and LuminPack: List, HashSet,
      Dictionary<int|string|Guid|struct, IFoo> at 1 / 4 / 12 / 32 / 100, 20 subtypes random and sorted; IL2CPP C++
      (the chain inline, no VirtualActionInvoker per element); NinoGen.Dispatch.g.cs size and the generator benchmark.

    PR 5 — strings as one kind (#347).

    • One cursor loop for StringFormatter and Utf8StringFormatter in elements and pairs, write, read and refill (§4.2).
    • Deletes: NinoDictionary.WriteStringPairs/TryWriteStringPair, Reader.ReadStringPairs x2, RefillStringPairs,
      ReadStrings as a special case, every typeof(StringFormatter) test outside NinoKind (10).
    • Measure: x64 and Arm64 listings (the cursor in registers; the Arm64 spill of the reader's six fields is the known
      trap), A/B of the 2x2 string/raw dictionaries (including Dictionary<string, int> reads, not on a fast path today),
      [NinoUtf8] members and lists, Dictionary<string, long> 100 pairs (Close the gaps LuminPack showed against the current Nino #305: 492 against LuminPack's 415 ns).

    PR 6 — reads fill storage through the view (#320, #350).

    • Hashed fill for every kind HashTables.Plan allows (§2.4): entries filled by the kind loop (scatter for fixed kinds),
      then HashTables.Build (buckets, collision count, duplicates). SortedList and PriorityQueue adopt for every raw
      or block pair with the default comparer (generic order and heap checks; the int vector checks kept as kernels).
      SortedDictionary's <= 8 gate resolved.
    • Deletes: NinoDictionary.AddRaw, HashSetFormatter.AddRaw/raw-only TryFill call sites (one Fill per view),
      BclDictionaries.TryReadSortedInt32Pairs/TryReadMatchingOrderedPairs/TrySplitOrderedPairs and Code's TypeCode
      switch, PriorityQueueHeap.TryAdopt(PriorityQueue<int,int>)'s fixed signature.
    • Alignment: scatters store aligned to the entries where whole entries reach a vector boundary; dense fills keep
      CopyToNew (aligned destination, AMD downward copy).
    • Measure: HashFloodingTests and the malicious corpus (collision limits, duplicates, null keys) unchanged; fuzz;
      runtime-internals tests on .NET 8/10 x64/Arm64/Arm32/x86, Mono x64/Arm64; A/B at 1 / 4 / 12 / 32 / 100 pairs with
      int and string keys against main and LuminPack (Read dictionaries of polymorphic values as fast as LuminPack: fill entries, then buckets #320's table), sorted lists and priority queues of <long, double>,
      <int, string>, <int, MyRaw>, enums and floats (NaN ordering, Extend the int-only SortedList and PriorityQueue paths to every raw pair #350).

    PR 7 — non-contiguous collections on the layer, and prefetch in every class loop (#355 items 1 and 3).

    • ReadOnlySequence, LinkedList, SortedSet/SortedDictionary, immutable trees, ConcurrentStack, plain
      IEnumerable per §7.2 (walk or gathered runs, whichever measures faster per kind); prefetch gate and runs in the
      class kinds and pair values (§4.6).
    • Deletes: NinoCollections.WriteEnumerated's per-element WriteOne, BclCollections.AddEach's kind branches, the
      Immutable package's per-formatter element loops (ImmutableHashSet/Queue/Stack/Dictionary/SortedSet/SortedDictionary),
      NinoPrefetch.Write/Read as separate array and list loops (the top-level calls reach the same kind loop).
    • Measure: walk against gather per collection kind (local probes to choose, runner A/B to land); the prefetch matrix of
      §4.6 with the off control and the property off; CommonTypes Orders and Tree with the property on; Arm64 reverse
      reads (ReverseReadIsLocal).

    Issue map:

    issue PR
    #345 PR 0 (.NET 8+), PR 1 (netstandard), PR 4 (pair loop over every dictionary-like view)
    #346 PR 1
    #347 PR 5
    #348 PR 2
    #349 PR 3 (HashSet, ImmutableArray writes), PR 4 (polymorphic sets and BCL dictionary values), PR 6 (HashSet reads)
    #350 PR 3 (SortedList and PriorityQueue writes), PR 6 (adopt reads)
    #295 PR 2
    #320 PR 6
    #355 PRs 1-7; skills checklist in each PR's docs(skills) commit

    Expected count: element-kind decisions from about 60 sites to one class; per-element loops from 57 call-site lines in
    20 files plus 5 string loops plus 3 generated loops per base, to six kinds x (write, read) in NinoElements, one pair
    loop per direction (plus refill) in NinoPairs, and two generated loops per base.


    10. Risks

    • Runtime layouts (runtime-internals). The in-use test reads a free-list encoding (Next < -1 on CoreCLR since
      3.0) that Mono's and IL2CPP's class libraries may encode differently; CollectionViews.Checks gains a check per
      candidate with removed entries (known contents, then the walk must match the enumerator), and a failed check keeps
      today's behavior (dense only when count == bound, else enumerator or rented copy). Mirrors, Retype and "never an
      instance method on a mirrored object" (Mono aborts) apply to any new mirror (ConcurrentQueue slots).
    • 32-bit. Layout strides differ (entries of references 12 not 24 bytes; fastModMultiplier absent on x86, the
      field LuminPack skips); every layout's offsets come from NinoBlocks.Offset on a default entry, never constants;
      Arm32 under qemu and x86 Windows run the runtime tests.
    • Unity startup checks. More checks at first use add startup time on IL2CPP (ObjectTypes.Passes per candidate):
      keep them lazy per collection kind, as now. Generic virtual methods on IL2CPP (§5.3) are verified in C++ before PR 1
      relies on them; fallback stated there.
    • The netstandard Unity DLLs must be refreshed in every PR touching Nino.Core or the generator, and Unity 2022.3's
      Roslyn 4.3 (interceptors off) must still compile the generated overrides (C# 8 features only in generated code
      compiled there).
    • IL2CPP code size. Instantiation per (T, TFormatter, TLayout) multiplies methods (IL2CPP compiles every method of
      a type); measure the player's binary size per PR, keep layouts few (§2.1 lists them all).
    • Bytes. Order on the wire is the enumeration order: entries index order skipping free entries (Dictionary,
      HashSet), head to tail (Queue), bottom to top (Stack), heap order (PriorityQueue), sorted order (SortedList). Golden
      bytes, conformance, and the Go/Rust/TypeScript runtimes reading the corpus prove nothing moved; no PR changes the
      wire format (no Wire-Format: trailer anywhere in the series).
    • Hostile input. Every fill keeps TryReadLength with the kind's MinWire, the amplification budget
      (Heavy/Capacity), collision counting, duplicate and null-key rejection, uninitialized arrays only where every byte
      is written (CopiedWhole); a scatter that rejects data must leave no stale heap memory in a caller-visible object
      (publish after fill, as NewOrSame/Publish do).
    • Register pressure. Generic loops over two layouts may spill on Arm64 where special loops did not (the reason the
      string loops exist): listings per CPU in PR 5 and PR 4.
    • Inlining budgets. NinoElements.Write is inlined into every collection formatter; a switch over kinds must fold
      to one arm before the JIT sizes the method (static readonly fields fold at import; methods returning them did not:
      HeavyElements comment).

    11. Decisions for the owner

    1. Public API: add default methods (generic) to INinoFormatter<T> in every build, and replace (remove) the public
      INinoElementsFormatter<T> and INinoPairsFormatter from perf(generator): write dictionaries of a polymorphic value in one generated loop #325 with them and one marker. Both are
      EditorBrowsable(Never), but removal is the owner's call.
    2. Block formatters forward one line (WriteFixedValue => WriteFixed) so netstandard's per-element call is direct;
      the loop stays in Nino.Core. Is that within the earlier "no loop in the formatter" decision?
    3. IL2CPP generic virtual methods: accept the generic WriteElements/WritePairs on netstandard once the C++ shows
      direct calls, with the non-generic strided fallback otherwise.
    4. Polymorphic dispatch: keep the chain (no indirect call) unless the runner probe shows a form without one that
      wins everywhere; a user-ordered chain (an attribute or declaration hint) would be new public API.
    5. Prefetch in nested collections under NinoPrefetchLargeCollections: accept one compare per collection in opted-in
      projects (zero elsewhere), measured on CommonTypes with the property on.
    6. ConcurrentQueue segments in place: in or out of scope (concurrency-sensitive layout; the snapshot is the cost).
    7. IL2CPP binary size budget for the extra instantiations.
    8. Dedicated formatters (UnmanagedArrayFormatter, NullableArrayFormatter, raw/nullable ListFormatters): bound
      to the general formatters where the shared path matches them (public types stay; the binding table changes).

    Generated by Claude Code

  5. JasonXuDeveloper commented on Nov 16, 2026

    @JasonXuDeveloper
    OwnerAuthor

    Decided:

    • Both directions. Reads and writes are optimized together.
    • Pooled buffers. Wherever elements are gathered into a span (linked lists, trees, IEnumerable, runs of class elements), the buffer is rented from a pool (ArrayPool or Nino's own) and returned, never allocated per call. Each gather copies at most a bounded run, so a huge collection never rents one huge buffer.
    • Fresh dictionaries. A new dictionary fills all its entries first and builds the buckets in one pass at the end, keeping the collision counting and the duplicate-key rejection.
    • Fast creation for every collection Nino reads into new. Wherever a collection is created new, look for the same kind of fast creation that SortedSet already has (its red-black tree built in one pass): SortedDictionary, SortedList, PriorityQueue, Queue, Stack, LinkedList, the immutable collections, ConcurrentDictionary and ConcurrentQueue. Each one behind a startup check with the public API as fallback (runtime-internals).
    • Dispatch. Research a faster form beyond the exact-type chain.
    • The rest of the design is accepted: the new methods on INinoFormatter<T>, the one-line forwards in block formatters, the IL2CPP check with its fallback, prefetch in the class loops, ConcurrentQueue in scope, and the dedicated array and list formatters moved onto the shared path. A larger IL2CPP binary is acceptable.

    Generated by Claude Code

  6. JasonXuDeveloper commented on Nov 18, 2026

    @JasonXuDeveloper
    OwnerAuthor

    This issue now comes right after the ImmutableStack write of #305. The rest of #305 is paused until the layer is in.

    The same rule wherever it applies, not only in collections. Anything that solves one job in several hand-written copies gets one generic path the compiler specializes:

    Before the first pull request, a redundancy audit (audit-redundancy, audit-core) lists every remaining place that decides an element kind itself or carries a loop of its own, and adds it here.

    Planned order, one pull request per step, each with tests, a machine-code proof and an A/B per CPU:

    1. Reach formatter capabilities through constrained calls, never interface casts #346: capabilities through constrained calls on the formatter's struct type, never interface casts. Devirtualized on .NET and netstandard (IL2CPP, Mono). Everything below builds on this.
    2. The storage view and one write loop per element kind over it: arrays, lists, spans, queue and stack rings, HashSet and Dictionary entries, the PriorityQueue heap, SortedList. Alignment in every loop, prefetch for classes.
    3. The same for reads, with fresh collections built through their internals: fill, then link or build, every hostile-input check kept. This brings in Give HashSet, ImmutableArray and the BCL dictionaries the paths List and Dictionary have #349 and Extend the int-only SortedList and PriorityQueue paths to every raw pair #350.
    4. Write dictionaries of polymorphic values through one generic pair loop for every key type #345 and Write and read pairs and strings through one cursor loop for every formatter #347 as instances of the layer's pair and element loops.
    5. Make every fixed-size formatter a block formatter, and let blocks compose #348 and Route every collection of T? and NinoNullable<T> through the shared block element path #295: blocks and slots as element kinds of the same path.
    6. The non-contiguous ones gathered into the layer: ReadOnlySequence by segment; LinkedList, SortedSet and the immutable trees by runs of nodes; plain enumerables. Pooled memory, a bounded copy per step.
    7. Dispatch: the fastest form with no indirect call per element, measured against LuminPack. Then Close the gaps LuminPack showed against the current Nino #305 resumes on the new layer.

    Generated by Claude Code

  7. 127 remaining items

  8. JasonXuDeveloper commented on Nov 22, 2026

    @JasonXuDeveloper
    OwnerAuthor

    Merged into feat/storage-layer:

    Still open before this issue's PR into main:


    Generated by Claude Code

  9. JasonXuDeveloper commented on Nov 22, 2026

    @JasonXuDeveloper
    OwnerAuthor

    #447 is merged into feat/storage-layer (352c076). All CI is green, Unity and WebGL included.

    More types now get a flat body, on the one item chain from #446:

    • Properties with direct get/set, through NinoPropertyAt over INinoProperty<TValue>. They never join a block.
    • Raw T? members, as slot items. A body with a slot and no string is flat too.
    • Structs, for runs only (NinoFlatValues through the HasFlat/WriteFlat/ReadFlat hooks).
    • Generic types whose members' formatters are closed, flat when every type argument is a value type.

    The bytes are unchanged; every new shape has a byte twin. No benchmark method's listing is worse, and there are no new inline failures.

    Step C is in progress:


    Generated by Claude Code

  10. JasonXuDeveloper commented on Nov 22, 2026

    @JasonXuDeveloper
    OwnerAuthor

    The runner A/B of feat/storage-layer against the previous main shows regressions. This blocks the PR into main until they are fixed.

    Run 44979508452 compares head c6eff3b (after #443) with base bcc00f8 (main 9540e0b plus LuminPack 2.0.0-rc.2, which head's benchmark project needs; Nino's code is main's). It covers the whole Nino suite, 3 rounds, head min ÷ base min. The first 8 jobs are done.

    • Floor (base against base): clean. Neoverse-N2 geomean 0.991, Intel 1.009; the largest is 1.22 on the bimodal Scattered.
    • Head against base: geomean about 1.00 on every CPU (Neoverse-N2 0.993, Xeon 0.999/1.000, EPYC 9V74 1.002/1.002, EPYC 7763 1.010). The cases below are slower on every x64 runner:
    Case x64 runners Neoverse-N2
    AppDataTest.NinoSerializePlayers 1.75–2.5 1.57
    CollectionsTest.NinoDeserializeNullableHashSetInts 2.2–2.6 2.52
    FixedSizeTest.NinoDeserializeFixedStruct 1.4–3.0 –
    WorkloadTest.NinoSerialize ProfileCache / LogBatch / EventStream / MediaContent 1.3–1.9 1.2–1.4
    SimpleTest.NinoSerializeSimpleClass(es) 1.44–1.60 1.18–1.21
    VersionTolerantTest.NinoSerializeTolerantClass(es) 1.4–1.5 1.19–1.23
    NullableTest.NinoSerializeNullableObjects 1.43–1.55 1.21
    ExternalBufferTest.NinoSerializeExternalClasses 1.35–1.38 1.16
    ScatteredTest.NinoSerializeScatteredItems 2.0–2.3 (EPYC) –
    NullableTest.NinoNullableDeserializeNullableStruct 12.4 (EPYC 7763 only) –

    Most of these are the top-level serialize of single class objects, plus a few reads. Local timing had shown them on par, but only against each step's own base branch, never against main.

    Next:

    The remaining jobs (EPYC floors and more samples) are still running.


    Generated by Claude Code

  11. added a commit that references this issue on Nov 22, 2026
  12. JasonXuDeveloper commented on Nov 22, 2026

    @JasonXuDeveloper
    OwnerAuthor

    #450 merged into feat/storage-layer (e92a7d9), with every check green, Unity and WebGL included.

    Keyed, version-tolerant and nested bodies now take the item chain for their runs. Each is a leaf on the chain (NinoRegionItem, NinoTolerantItem, NinoKeyItem in NinoEntriesItem, a nested type's chain as one item), not a new loop. The bytes do not change.

    Also in #450:

    Local numbers against main at 1,000 elements: writes 0.62–0.82, reads 0.77–1.00 at Tier1.

    Follow-ups, as sub-issues:

    Still before the PR into main:


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corearea: generatorkind: perfkind: refactor

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions