Repository navigation
Description
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/Tupleof 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.ValueTupleandKeyValuePairare 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
WriteElementsand 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 onINinoFormatter<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, againstmain, 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; QueueandStack(rings and arrays);HashSetandDictionary(their entries arrays);PriorityQueue(its heap),SortedList(its two arrays),CollectionandObservableCollection(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>,SortedSetand 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:
- unmanaged / raw: one block with the SIMD kernels;
T?of rawT, orNinoNullable<T>: the slot kernels;- a block formatter (fixed size, composed): the block path;
- a class: polymorphic dispatch inline where the base dispatches, and prefetch under NinoPrefetch's gate;
- 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, theArrayBufferof 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-internalsproves the layout, with every hostile-input check kept:Dictionaryfills 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;SortedSetbuilds its tree in one pass;- the same is sought for
HashSetof every element kind,ConcurrentDictionary,SortedDictionary,SortedList,PriorityQueue,LinkedListand 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.
- Design, with the order of the pull requests
- One pull request per step, each with tests, a machine-code proof and an A/B
- The rule recorded:
optimize("One storage layer for every collection"),audit-corechecks it, AGENTS.md points to it (branch claude/storage-layer-rule) - The skills record the view and the per-kind loops as they land (
optimize,runtime-internals) - Reads: one read loop per element kind over the view, with fresh collections built through their internals (fill, then link)
- Gathering into a span: pooled memory and a bounded copy per step, measured on sequences, trees and linked lists
- Alignment in every loop, not only the SIMD ones, where it measures faster
- User collection types join the layer. The design is in the comments of 2026-11-18:
Generated by Claude Code
Activity
JasonXuDeveloper commentedon Nov 16, 2026
Design, in order of pull requests. Each lands with tests,
asm.py compareshowing 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.claude/dictionary-pairs-general).NinoKind<T, TFormatter>, one set ofstatic readonlytraits, tested withtypeofonly: raw → slot → block → string → polymorphic → general. Capabilities become default methods onINinoFormatter<T>in every build, reached by constrained calls on the formatter's struct type. The netstandard pair loop. The first check is the IL2CPP C++ for those calls: Unity's docs say value-type instantiations are never shared, and a known issue boxes generic virtual methods on structs.ref first, countplus a layout type giving the offset and the in-use test) and the write loops for every contiguous collection. SIMD runs directly on contiguous segments, strided entries go through the existing gather and scatter, and stores are aligned per segment (the 4K rule on AMD).ReadOnlySequencesegment by segment, linked lists and trees walked into runs,IEnumerablebuffered, and prefetch in every class loop.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
JasonXuDeveloper commentedon Nov 16, 2026
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
NinoKind<T, TFormatter>), and where it is repeated todaystatic readonlytraits, IL2CPP, partial types1. What is there today
The element-kind decision and the loops are spread over the collection formatters. Counted on 9158f97:
WriteOne/ReadOne/AddUniqueinside a loop: 57 across 20 files(
NinoDictionary14,BclDictionaries10,NinoElements7,PriorityQueueFormatter4,LookupFormatters4,KeyValuePairFormatter4,HashSetFormatter3,BclCollections3,DictionaryLikeFormatter3, Immutable 5, ...),plus 4 hand-written string loops in
Reader.Strings.cs(ReadStrings,ReadStringPairsx2,RefillStringPairs)and
WriteStringPairs/TryWriteStringPairinNinoDictionary, plus 3 generated loops per polymorphic base(
WriteElements,__WritePairs,__WritePairsThroughDispatch).RawFormatter.Is<in 13 files, slots(
SlotStride/NinoSlots) in 8,typeof(StringFormatter)in 3 (10 tests),typeof(DateTimeOffsetFormatter)4 testsin
NinoElements,INinoElementsFormatter/INinoPairsFormattercasts in 2, and the formatter binding table picksdedicated formatters per kind (
UnmanagedArrayFormatter,NullableArrayFormatter, the raw and nullableListFormatters).List(ListAccess),Queuering (two spans),Stackarray,HashSet/Dictionaryentries (only when no entry is free:
CollectionFields.Entriesreturns null whencount != bound),SortedListarrays (int and same-type integer keys only),
PriorityQueueheap (<int,int>only),Collection<T>'s list,multi-dim arrays,
ImmutableArray(value types only: references take aforeach).NinoBlockCollections.WriteAll<TEntry, TProjection>overSetEntryBlock<T>,SetEntryBytes<T>,MapEntryBlock<TKey,TValue>: the block plan's permute kernels with a map shifted by the value'soffset in the entry. This is the gather the design generalizes.
NinoBlockPlan.Formatter.WriteFixed(a boxedinterface, 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 atall (
#if NET8_0_OR_GREATERin 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 TEntryto its first entry and acount. How an element lies in an entry is the layout, a stateless struct type argument whose members are all
JIT-time constants:
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
reffields outside ref structs, andnetstandard2.1 has no
allows ref struct), so segments are passed as(ref TEntry first, int count)and a view of twosegments (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
T[],Span,Memory,ArraySegment,ImmutableArray,T[,]..Same<T>List<T>,Collection<T>/ObservableCollection<T>(wrapped list)Same<T>ListAccess.AsSpan,CollectionFields.ListQueue<T>Same<T>Stack<T>Same<T>HashSet<T>SetValue<T>Densewhencount == bound, else in-use testDictionary<K,V>MapKey+MapValueSortedList<K,V>Same<K>,Same<V>PriorityQueue<E,P>Item1,Item2ConcurrentQueue<T>(andBlockingCollectionover it)QueueSlot<T>ReadOnlySequence<T>/ReadOnlySequence<byte>Same<T>LinkedList,SortedSet, immutable trees,IEnumerableSame<T>over a rented span2.3 Pairs
A pair loop is one loop over two element streams advanced in lockstep:
(ref TKeyEntry k, TKeyLayout)and(ref TValueEntry v, TValueLayout). ADictionarypasses the sameref entries[0]for both withMapKey/MapValue;a
SortedListpassesref keys[0]andref values[0]withSame<K>/Same<V>; aPriorityQueuepasses the nodearray 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:
from 0): one dense segment, the element loop reads into it (
NinoElements.Readtoday;NinoCollectionViews.ReadIntoalready does this for
QueueandStack).SortedList's two arrays, aPriorityQueue's nodearray): allocated by the size rules that exist (
MinWireSize,Heavy,Capacity,NewOrSame/Publishforuninitialized arrays), filled through a dense segment, then published (count, version, head, tail).
HashSet/Dictionary(default or seeded comparer) sized for the count. Its entriesarray is a strided segment (
SetValue,MapKey/MapValue): the element loop reads the keys and values straightinto the entries, then
HashTables.Buildhashes them and links the buckets in one pass, counting collisionsagainst
MaxHashCollisionsand rejecting duplicates exactly asHashTables.Filldoes 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.Plansays the BCLguards 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.ReadAllwith the projected map (the read twin of theMapEntryBlockgather); slots read into a rented dense run of at most 256 elements through the slot kernel, thenmove 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:
On .NET 8+ Tier1 folds every
static readonlyof an initialized class, soswitch (NinoKind<T,TF>.Value)leaves onearm in the listing. For value types the existing intrinsic tests (
RawFormatter.Is,IsReferenceOrContainsReferences)stay in front, as
NinoElementsalready does, so shared code over a classTnever loads the field (one runtimelookup 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)
NinoElements.Write/Read/WriteBlock/BlockStride/ReadOverwrites/CopiedWhole/MinWireSize/MinHashedSize/MinSingleSize,Traits<T,TF>,NinoSlots<T,TF>.FixedStrideNinoDictionary.Write(raw+raw, raw+string, string+raw,INinoPairsFormatter, general),Read(raw+raw, raw+string, string+string, general),Refill(raw+string)HashSetFormatter.Serialize(raw entries, slots,WritesOnLocal, enumerator),Deserialize(raw fill, slots, plan, general)QueueFormatter,StackFormatter,CollectionFormatter,ConcurrentStackFormatter,ProducerConsumerFormatter(BlockStride,SlotStride,ReadOne)BclCollections(LinkedList raw ring / slots / each; SortedSet packed tree),BclDictionaries(SortedList TypeCode switch,<int,int>, SortedDictionary<= 8byte gate)PriorityQueueFormatter+PriorityQueueHeap(intPair,TryAdopt(PriorityQueue<int,int>))KeyValuePairFormatter,TupleFormatters.g.cs(26RawFormatter.Is)Nino.Immutable:ImmutableArrayFormatter(!typeof(T).IsValueType->foreach),ImmutableCollections, HashSet/Dictionary/Queue/Stack formattersReader.Strings.csReadStrings,ReadStringPairsx2,RefillStringPairs;NinoDictionary.WriteStringPairstypeof(StringFormatter)NinoElements.Writedefault(TFormatter) is INinoElementsFormatter<T>;NinoDictionary.Writeis INinoPairsFormatterDispatchEmitter.EmitWriteElements(span only),__WritePairs(dictionary only),FormatterTraitsOfname table (Flat, PreservesReadContext)BuiltInFormatters/NinoFormatterResolverpickUnmanagedArrayFormatter,NullableArrayFormatter, raw/nullableListFormattersINinoRawArrayFormatterentry, external writes), else bound to the general array/list formatter4. The per-element-kind loops
All loops live in one file pair,
Internal/Collections/Traversal/NinoElements.cs(writes) andNinoElements.Read.cs(reads), generic over
<TEntry, TLayout, T, TFormatter>. The collection formatters call onlyNinoElements.Write(ref first, count, ref writer)/Read(...)per segment andNinoPairs.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 oneReserveCountedfor a wholering, as
QueueFormatterdoes now):NinoLayout<T>.CopyToWire(aNinoUnsafe.Copyblock 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 forSetEntryBlock,MapEntryBlock)DateTimeOffset, composed tuples and pairs after PR 2)NinoBlockCollections.WriteAll<T,TF>(Groups, Lanes, Permute64; Burst kernels viaNinoKernelson netstandard)Projected<...>: the map isNinoBlockMap.Block<T,TF>shifted byTLayout.Offset(the mergeNinoBlockMap.Blockdoes for nested structs today)NinoNullables<T>kernels (WriteSlots, lined stores,CopyRealigned)SlotsWriteInPlace: gather the raw values as bytes (SetEntryBytestoday) into the reservation, then the slot kernel in place (1,000int?: 227 ns against 1,140 copied, local,HashSetFormatter.WriteSlots); otherwise a rented dense copy of at most 256Read (one
TakeElementsper segment,precheckedwhere the length check already proved the bytes):NinoUnsafe.CopyToNew(Arm64 short copy) orNinoChecks.Values+ copy for bools/UntrustedReadAllwith the projected raw map (scatter)NinoBlockCollections.ReadAll(aligned loads where measured: Ice LakeGroups.Aligned)ReadAllwith the projected mapNinoNullables.ReadPrecheckedWhich kernels run directly over a strided view: every
NinoBlockCollectionskernel (they already take a source map withoffsets per field and a source stride,
size), so raw and block values gather and scatter at full width; the plaincopy (
NinoUnsafe.Copy) and the slot kernels (NinoNullables,NinoMask.CopyLanes) assume a dense source and need thetwo-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
InUsefor the next run of in-use entries (a vector compareof the
Nextfields where the stride allows, else scalar) and calls the gather per run, so the kernels never see afree 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
StringFormatterandUtf8StringFormatter(an encoding type argument, the[NinoUtf8]form), writing with theFreeSpace/Commitpair (WriteStringPairs' technique: the cursorref byte dst, nuint pos, nuint endin registers, falling back to growing the buffer only when the longest form of a stringdoes not fit), and reading with
Reader.ReadStrings' register cursor. Pairs: the same cursor with the other item afixed-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 inlineNino.Core calls the base's generated loop through a constrained call on the formatter (§5), per segment:
The generated methods (
DispatchEmitter.EmitWriteElements) are the branch'sWritePairs<TKey, TKeyFormatter>generalized over the layout: the chain of exact type checks inline, the writer in a local,
IsDeeponce, the deep andunknown-subtype paths out of line, the in-use test inlined (a constant
truefor dense layouts, so arrays compile totoday's loop). The span overload
WriteElements(ReadOnlySpan<T>)is gone: a span isSame<T>over its reference.Reads stay in Nino.Core's general loop (
__ReadSubtypeinlined through the base formatter'sDeserialize): ahand-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 theWritesOnLocalchoice (value types and flatsealed classes on a local writer out of line; others on the caller's writer, measured: SelfTree 0.86x otherwise), and
ReadEachout of line with the reader by value. Same code as today'sNinoElementsloops, 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:
NinoUnsafe.BytesToAligned(ref dst, width)for slot kernels and copies,Lanes512.CopyRealignedwhere whole elements never land on a line (4-bytelength 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.
loads measured better (
NinoBlockCollections.Groupson Ice Lake: the source aligned,NinoBlockPlan.Aligned).Dense raw reads stay on
CopyToNew(aligned destination,rep movsbwhere FSRM wins, vectors elsewhere).NinoUnsafe.Aliases/CopyVectorsDown(perf(core): copy downward on AMD where a forward copy hits 4K aliasing #326): the gap between source and destination mod4 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.
vectors-nullable.md(source pinned at one phase perprocess, destination at offsets 0 and 1 of the buffer) and
BlockCopyTests' distance classes; a harness whose sourceand 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 theshared 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
Ta class,and dictionary values):
count > NinoKind<T,TF>.PrefetchThreshold(a quarter of the last-level cache over theelement's
PrefetchBytes, at least 1,024;int.MaxValuefor a formatter that is noINinoPrefetchFormatter/INinoObjectPrefetchFormatter, i.e. every project built withoutNinoPrefetchLargeCollections), then the 17-objectallocation-order sample (
NinoPrefetch.Scattered, both directions whereReverseReadIsLocal). Tier1 folds thethreshold, so in a project without the property the test is
count > int.MaxValueand vanishes; the netstandardbuild compiles it out (
NinoPrefetch.Supportedis false there: noprefetcht0, no scalar Arm64 prefetch).NinoPrefetch.Run(16): before each runAhead<TFormatter>prefetches the objects two runs ahead and the members of the next run.AheadandScatteredgain a byte stride (
nint stride = SizeOf<TEntry>, the element atTLayout.Offset): a dictionary's values areevery 24th byte, a set's every 16th; dense layouts pass
sizeof(object)and compile to today's code.Ahead(the generatedloop is unchanged; a call and a writer copy in and out per 16 elements, which only long scattered collections pay).
Refill); a freshread has nothing to prefetch (the sample sees nulls and declines, as now).
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 Treewith 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 castsThe branch
claude/dictionary-pairs-generalproved the form on .NET 10: a generic default interface method onINinoFormatter<T>, overridden by the generated struct, called asdefault(TValueFormatter).WritePairs<TKey, TKeyFormatter>(...), is a directcall(value-type key), or one generic-dictionary load per call from shared code overa 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 throughVIRTUAL_FUNC_PTR(35 / 49 / 94 / 215 / 693 ns at 1-100 pairsagainst 15 / 23 / 40 / 81 / 240).
Generalized,
INinoFormatter<T>carries a small set of default methods, in every build (netstandard2.1 included):WriteElements/WritePairswith the dispatch loops.KeyValuePairFormatter, tuples,DateTimeOffsetFormatter, the projections)override
WriteFixedValue/ReadFixedValuewith a forward to theirWriteFixed/ReadBlock.NinoBlockCollections'per-element fallback then calls
default(TFormatter).WriteFixedValue(...): a direct call on netstandard too, wheretoday it is
NinoBlockPlan.Formatter.WriteFixedthrough 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.NinoKind.Value == Kind.Slotand then byUnsafe.Asofnothing: they are Nino.Core's own structs, so the slot loop names them as type arguments of an internal generic
(
NinoNullables<T>.WriteSlotsforT?,NinoNullable<T>), selected bytypeof(TFormatter) == typeof(UnmanagedNullableFormatter<...>)folded insideNinoKind, not per site.called through a constrained call on a struct boxes
this.NinoKinddecides "overrides" by reflection once(
typeof(TFormatter).GetInterfaceMap(typeof(INinoFormatter<T>))targets declared on the struct, or a markerinterface:
INinoDispatchesfor polymorphic bases,INinoBlockFormatter<T>assignability for fixed values), neverby
default(TFormatter) is I.5.2
static readonlytraits on netstandard2.1 (IL2CPP, Mono)IL2CPP and Mono box
default(TFormatter)at eachistest and each cast (a GC allocation each time: the reasonTraits.ElementsandNinoSlots.Formatterexist). Every test therefore moves intoNinoKind<T, TFormatter>(andNinoBlockPlan,NinoPrefetch.Of), classes generic over the formatter (and the element), whose static initializers runtypeoftests once. On .NET 8+ Tier1 they are constants; under NativeAOT, IL2CPP and Mono they are one load each percollection. No
static readonly I Formatter = default(TF) as Isurvives: every per-element call becomes a constrainedcall (§5.1).
5.3 Default interface methods and IL2CPP
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).
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, anda constrained call on
FooFormatterinside it is resolved at conversion time toFooFormatter's own method: adirect C++ call, with the struct passed by pointer (no box). This is the same reason
default(TFormatter).Serializeis direct on IL2CPP today.
WriteElements<TEntry, TLayout>,WritePairs<...>): IL2CPP lists "some callsto 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 boxedvalues 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|InterfaceActionInvokerin thegenerated
Nino.Core.cppand the test assembly's cpp) before anything depends on it.(
WriteElements(ref T first, int count, nint stride, nint inUseOffset, ref Writer); references only, soTis thebase) and the pair loop stays Nino.Core's shared loop there. Fixed kinds do not depend on generic virtual methods at
all (
WriteFixedValueis not generic).5.4 Partial types
The generator already requires
partialfor private members on Unity and emits members into users' types.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.
__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
(
VirtualActionInvokerper element).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.
INinoLayout/kinds be static, but need .NET 7+; netstandard2.1and Unity cannot use them. The stateless-struct-instance form (
default(TLayout).Element(ref e)) is what works onboth 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)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 exaggeratethe dispatch's share; with real bodies the chain led (6.1).
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
switchis 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
where a virtual is a
VirtualActionInvokerwith no PGO and a jump table is an indirect jump).(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.
switch), whichthe 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.
DispatchTestbenchmark 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, chainby 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
Invokerper element) and theUnity 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/NinoPairsper segment)T[],Span,Memory,ArraySegment,ImmutableArray(references too: F6'sforeachgoes; strings must stay onpar with 264 ns / 100, the reason it was there, so the call is the inlined span path, not
ArrayFormatterout ofline), multi-dim (one segment;
MultiDimkeeps the shape header).List<T>,Collection<T>,ObservableCollection<T>(writes any subclass, reads the exact type: subclasses mayoverride
InsertItem),ReadOnlyCollectionover 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;ConcurrentStackkeeps its node walk (§7.2).HashSet<T>: entries walked for everyT(F5), free entries by the in-use test instead of the enumerator; reads: thehashed 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-usetest; 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/Deinterleavekernels kept as the kernels of 4-byte lanes), then theorder check through
Comparer<K>.Default(a vector kernel whereKis a signed integer), adopted when in order andno 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).
ConcurrentQueue<T>segments holdSlot { T Item; int SequenceNumber }arrays, a strided view with anin-use test by sequence number; the snapshot (
ToArray) is the measured cost today (4,200 against 3,760 ns per1,000
int?). Optional (§11): concurrency rules make the in-place walk a version-checked snapshot at best.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>(andReadOnlySequence<byte>): eachReadOnlyMemory<T>segment is a dense span: one callof 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 valuestraight into the one reservation (
WriteLinkedRingtoday, pairs of nodes at >= 32: jit-collections.md); a gatherinto 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
HashSetslots).Class kinds: gather the references into a rented span of at most
Runx 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 loopinto a rented dense run first for fixed kinds.
SortedSet<T>andSortedDictionary: the red-black tree in order. Raw values already take the packed treewriter (
SortedSetNodes,TryWritePackedTree); the<= 8byte gate ofSortedDictionary(F7) is aligned withSortedSet's rule (any raw unpadded type) once its reason is found. Other kinds: an in-order walk gathering intorented runs of 256, then the dense loop per run (one
Aheadgate per run for classes). Reads:SortedSetTreesbuildsthe tree in one pass from a sorted dense run (exists), the run read by the kind loop.
ImmutableList,ImmutableHashSet/Dictionary,ImmutableSortedSet/Dictionary): walk thenodes (Nino.Immutable's
HashTrees/SortedTreesmirrors) gathering into rented runs; reads build the tree from adense run (exists for hash and sorted trees).
ImmutableQueue/ImmutableStack: linked; same asLinkedList.ConcurrentStack<T>: the captured node chain (ConcurrentStackNodes): counted, reserved once, walked bottom totop for raw values (exists); other kinds gathered into runs.
IEnumerable<T>(no list, array or known collection behind it): buffered into a rented span (countknown:
ICollection<T>.CopyTointo a rented array,NinoCollections.RentCopied; unknown: grow a rented buffer),then the dense loop. The single extra pass costs less than an enumerator
MoveNextinterleaved with the kernels, andit 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 (
WriteLinkedRingpairs at >= 32,HashSetFormatter.WriteSlotsgather-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 aDictionary<K,V>member it emits a loop overLuminPackMarshal.GetDictionaryView(value)._entries(falling back to theenumerator for sparse dictionaries),
writer.EnsureAdditionalCapacity(count * (sizeof K + sizeof V))once forunmanaged pairs, and on read creates
new Dictionary(length), reads keys and values straight into_entries[i], thenTryRebuildFreshDictionaryBucketsbuilds the buckets in one pass with a collision count (falling back toAddwhen thelayout 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 throughUnsafe.CopyBlockUnaligned.LuminPackEvaluatorcan compute sizes ahead (a second pass).Polymorphism.
LuminPackUnionDispatchCodeGeneratoremits into the user's partial types aninternal virtual __LuminPackUnionSerialize_X(ref LuminPackWriter)on the root andinternal (sealed) overrideon each member with itsid 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.
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.
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).
9. Migration plan
Every PR lands on its own: tests (unit, runtime internals with a
FastPathsrow for each new layout, conformance andgolden bytes unchanged, fuzz corpus), the machine code (
python3 benchmarks/asm/asm.py compare origin/main: no methodworse; the listings named per PR), a runner A/B per CPU (the
benchmarkskill: one A/B in flight, fewest lines), theUnity 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 generatedWritePairs<TKey, TKeyFormatter>for every key (.NET 8+), deletesWritePairs32/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 —
NinoKindand the capability contract (#346).NinoKind<T,TFormatter>(§3.1) and the default methods onINinoFormatter<T>in every build (§5.1); generatedpolymorphic bases implement
WriteElements/WritePairsin netstandard too (the#if NET8_0_OR_GREATERaround thegenerated pair loop and in
NinoDictionary.Writegoes); block formatters forwardWriteFixedValue/ReadFixedValue.default(TFormatter) is INinoElementsFormatter<T>and its cast,Traits.Elements(netstandard), theis INinoPairsFormattergate's cast,NinoBlockPlan.Formatteras a call target (WriteValue/ReadValuebecomeconstrained calls),
NinoSlots.Formatteras a call target,NinoElements.Traits(moved intoNinoKind).INinoElementsFormatter<T>andINinoPairsFormatterare replaced by the default methods and one marker (owner'scall, public).
CORINFO_HELP_ISINSTANCEOF*, box or indirect call per element; IL2CPPC++ of unity.yml: direct calls, no
Box, noil2cpp_codegen_get_generic_virtual_methodfor 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).
DateTimeOffsetFormatterbecomes a block formatter;KeyValuePairFormatterand the tools/CodeGen tuple formatterstake items that are raw or blocks (
NinoBlockMap.Block),FixedSizethe sum;T?andNinoNullable<T>become aKind.Slotthe shared path moves in every collection (Route every collection of T? and NinoNullable<T> through the shared block element path #295);SetEntryBlock,SetEntryBytes,MapEntryBlockbecome one
Projected<TEntry, TLayout, T, TFormatter>block.typeof(DateTimeOffsetFormatter)tests andDateTimeOffsetFormatter.WriteAll/ReadAllas a case;the 26 raw-only tests in
TupleFormatters.g.cs(one composition rule in tools/CodeGen);NullableArrayFormatterandthe raw-nullable list formatter where the shared path matches them (kept only for what it cannot do); the three entry
projection structs.
CopyRealignedapply to every collection of slots; measured with thephase controls (§4.5).
NinoBlockMap.Checked);A/B of
List<(int, DateTimeOffset)>,KeyValuePair<int, BlockStruct>[], dictionary values of blocks, every Route every collection of T? and NinoNullable<T> through the shared block element path #295collection of
int?/Vec3?/NinoNullable<long>(Queue, Stack, HashSet, LinkedList, Memory, multi-dim,ImmutableArray, concurrent); Burst kernels on netstandard (Add Burst kernels for raw nullable runs and NinoNullable<T> runs #280) and every SIMD target (Give every SIMD target a vector path for nullable runs of any stride and for NinoNullable<T> runs #279).
PR 3 — the storage view and the write loops over it (#349 F5/F6, #355 core).
INinoLayoutand the layouts (§2.1);NinoElements.Write(ref first, count)per kind over a layout (§4); everycontiguous collection's write calls it per segment (§7.1); free entries by the in-use test (startup-checked per
runtime layout, §10).
HashSetFormatter.WriteEnumerated/WriteSlots/WriteEach;NinoDictionary.WriteRaw/WriteEnumerated/ WritePairs(oneNinoPairs.Write);QueueFormatter/StackFormatter/CollectionFormatter/ConcurrentStackFormatter/
ProducerConsumerFormatterelement-kind branches andWriteOneloops;BclDictionaries.WriteSortedListRaw/Scalarand the
TypeCodesplit;PriorityQueueHeap.TryWrite'sintPaircase;ImmutableArrayFormatter'sforeach;NinoElements.WriteOne(no per-element slot interface call left anywhere).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 holdingremoved 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>andWritePairs<TKE, TKL, TKey, TKeyFormatter, TVE, TVL>(§4.3) replace the spanloop and the dictionary-only pair loop; sets, rings,
ImmutableArray,SortedListandPriorityQueuevalues of abase get the inline dispatch.
WriteElements(ReadOnlySpan<T>),__WritePairsThroughDispatch(free entries are in-use tests now; thedeep path stays), the enumerator path in generated code.
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
VirtualActionInvokerper element);NinoGen.Dispatch.g.cssize and the generator benchmark.PR 5 — strings as one kind (#347).
StringFormatterandUtf8StringFormatterin elements and pairs, write, read and refill (§4.2).NinoDictionary.WriteStringPairs/TryWriteStringPair,Reader.ReadStringPairsx2,RefillStringPairs,ReadStringsas a special case, everytypeof(StringFormatter)test outsideNinoKind(10).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).
HashTables.Planallows (§2.4): entries filled by the kind loop (scatter for fixed kinds),then
HashTables.Build(buckets, collision count, duplicates).SortedListandPriorityQueueadopt for every rawor block pair with the default comparer (generic order and heap checks; the int vector checks kept as kernels).
SortedDictionary's<= 8gate resolved.NinoDictionary.AddRaw,HashSetFormatter.AddRaw/raw-onlyTryFillcall sites (oneFillper view),BclDictionaries.TryReadSortedInt32Pairs/TryReadMatchingOrderedPairs/TrySplitOrderedPairsandCode'sTypeCodeswitch,
PriorityQueueHeap.TryAdopt(PriorityQueue<int,int>)'s fixed signature.CopyToNew(aligned destination, AMD downward copy).HashFloodingTestsand 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, plainIEnumerableper §7.2 (walk or gathered runs, whichever measures faster per kind); prefetch gate and runs in theclass kinds and pair values (§4.6).
NinoCollections.WriteEnumerated's per-elementWriteOne,BclCollections.AddEach's kind branches, theImmutable package's per-formatter element loops (
ImmutableHashSet/Queue/Stack/Dictionary/SortedSet/SortedDictionary),NinoPrefetch.Write/Readas separate array and list loops (the top-level calls reach the same kind loop).§4.6 with the off control and the property off; CommonTypes Orders and Tree with the property on; Arm64 reverse
reads (
ReverseReadIsLocal).Issue map:
docs(skills)commitExpected 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 pairloop per direction (plus refill) in
NinoPairs, and two generated loops per base.10. Risks
runtime-internals). The in-use test reads a free-list encoding (Next < -1on CoreCLR since3.0) that Mono's and IL2CPP's class libraries may encode differently;
CollectionViews.Checksgains a check percandidate 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,Retypeand "never aninstance method on a mirrored object" (Mono aborts) apply to any new mirror (ConcurrentQueue slots).
fastModMultiplierabsent on x86, thefield LuminPack skips); every layout's offsets come from
NinoBlocks.Offseton a default entry, never constants;Arm32 under qemu and x86 Windows run the runtime tests.
ObjectTypes.Passesper 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.
Roslyn 4.3 (interceptors off) must still compile the generated overrides (C# 8 features only in generated code
compiled there).
a type); measure the player's binary size per PR, keep layouts few (§2.1 lists them all).
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).TryReadLengthwith the kind'sMinWire, the amplification budget(
Heavy/Capacity), collision counting, duplicate and null-key rejection, uninitialized arrays only where every byteis written (
CopiedWhole); a scatter that rejects data must leave no stale heap memory in a caller-visible object(publish after fill, as
NewOrSame/Publishdo).string loops exist): listings per CPU in PR 5 and PR 4.
NinoElements.Writeis inlined into every collection formatter; a switch over kinds must foldto one arm before the JIT sizes the method (static readonly fields fold at import; methods returning them did not:
HeavyElementscomment).11. Decisions for the owner
INinoFormatter<T>in every build, and replace (remove) the publicINinoElementsFormatter<T>andINinoPairsFormatterfrom perf(generator): write dictionaries of a polymorphic value in one generated loop #325 with them and one marker. Both areEditorBrowsable(Never), but removal is the owner's call.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?
WriteElements/WritePairson netstandard once the C++ showsdirect calls, with the non-generic strided fallback otherwise.
wins everywhere; a user-ordered chain (an attribute or declaration hint) would be new public API.
NinoPrefetchLargeCollections: accept one compare per collection in opted-inprojects (zero elsewhere), measured on CommonTypes with the property on.
ConcurrentQueuesegments in place: in or out of scope (concurrency-sensitive layout; the snapshot is the cost).UnmanagedArrayFormatter,NullableArrayFormatter, raw/nullableListFormatters): boundto the general formatters where the shared path matches them (public types stay; the binding table changes).
Generated by Claude Code
JasonXuDeveloper commentedon Nov 16, 2026
Decided:
IEnumerable, runs of class elements), the buffer is rented from a pool (ArrayPoolor 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.SortedSetalready has (its red-black tree built in one pass):SortedDictionary,SortedList,PriorityQueue,Queue,Stack,LinkedList, the immutable collections,ConcurrentDictionaryandConcurrentQueue. Each one behind a startup check with the public API as fallback (runtime-internals).INinoFormatter<T>, the one-line forwards in block formatters, the IL2CPP check with its fallback, prefetch in the class loops,ConcurrentQueuein scope, and the dedicated array and list formatters moved onto the shared path. A larger IL2CPP binary is acceptable.Generated by Claude Code
JasonXuDeveloper commentedon Nov 18, 2026
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:
DateTimeOffsetjoin the block path (Make every fixed-size formatter a block formatter, and let blocks compose #348);T?andNinoNullable<T>as slot kinds of the same element path, not a fourth special case (Route every collection of T? and NinoNullable<T> through the shared block element path #295);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:
HashSetandDictionaryentries, thePriorityQueueheap,SortedList. Alignment in every loop, prefetch for classes.ReadOnlySequenceby segment;LinkedList,SortedSetand the immutable trees by runs of nodes; plain enumerables. Pooled memory, a bounded copy per step.Generated by Claude Code
docs(skills): unify the implementation first, then optimize the one path
127 remaining items
JasonXuDeveloper commentedon Nov 22, 2026
Merged into
feat/storage-layer:perf(generator): flat classes go through Nino.Core's flat kernels #443 (c6eff3b), the generator seam. Flat classes go through Nino.Core's flat kernels. Short ASCII UTF-8 strings take Nino's own vector path.
fix(bench): exit asm.py's startup hook only once the JIT is idle #445 (a0d5749), Find the cause of the rare free(): invalid pointer abort in asm dumps on feat/storage-layer #413's cause. The abort came from asm.py's startup hook exiting while the JIT was still writing listings, not from Nino.
refactor(core): one item chain for every composite #446 (1ecc5db), one item chain for every composite.
NinoItems(KeyValuePair, value tuples, entries) andNinoFlat(generated flat classes) composed the same thing twice. They are now one chain:INinoItemoverref byte;NinoItemAt<TMember, TItem, TNext>, plusNinoBlockAtfor blocks;Bytes are unchanged. Listings are equal or leaner, for example
string[]read: 779 B / 36 stack accesses → 699 / 30. All CI passed, Unity and WebGL included.Still open before this issue's PR into main:
T?/NinoNullable<T>members on the same chain. In progress.NinoNullablemembers and bools inside a class), and the rest of Keep hot paths fast where the JIT does not fold: NativeAOT, IL2CPP, Mono and FullOpts #436.Generated by Claude Code
perf(generator): properties, raw T?s, structs and generic types take …
JasonXuDeveloper commentedon Nov 22, 2026
#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:
NinoPropertyAtoverINinoProperty<TValue>. They never join a block.T?members, as slot items. A body with a slot and no string is flat too.NinoFlatValuesthrough theHasFlat/WriteFlat/ReadFlathooks).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:
NinoValueItem/NinoSlotItemreadNinoKind<T,TFormatter>.Stride, astatic readonly, once per element;Generated by Claude Code
JasonXuDeveloper commentedon Nov 22, 2026
The runner A/B of
feat/storage-layeragainst 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.
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
docs(skills): WIP: rules from #355 step C
docs(agents): record #355's rules on kernel composition, A/B against …
perf(core): WIP: flat struct runs shorter than MinRun element by elem…
perf(core): WIP: short flat struct runs take the loops of values one …
build(unity): rebuild the package DLLs for step C's chain leaves (#355)
docs(skills): short flat struct runs and measuring leaves against main (
perf(generator): keyed, version-tolerant and nested bodies take the i…
JasonXuDeveloper commentedon Nov 22, 2026
#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,NinoKeyIteminNinoEntriesItem, a nested type's chain as one item), not a new loop. The bytes do not change.Also in #450:
INinoItem.Leaves, and the chain stops after any item that may hand back.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:
UnmanagedNullableFormatter's statics at TC=0.Still before the PR into main:
claude/storage-fix.claude/storage-nobox.Generated by Claude Code