Span<T>一樣 ,构建交錯數組避開了非托管內存,托管BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是构建把一個托管數組對象視作一段更大的邏輯序列 。更進一步,托管避免每一次邏輯訪問都再走一次普通數組邊界檢查。上数组同時仍然讓這段存儲對 GC 可見。构建這兩種方案在某些場景下都能用 ,托管
在 .NET 裏 ,上数组數組數據區裏連續排列著塊結構體,构建
BigSpan 和 BigMemory
隻有持有存儲的托管類型還不夠 。但有些場景確實需要大塊連續數據 ,上数组
public BigArray(nint length){ if ((nuint)length > (nuint)MaxLength) { ThrowHelpers.ThrowOutOfRange(nameof(length)); } if (length <= Array.MaxLength) { _storage = new ElementChunk1<T>[length]; } else { _storage = CreateBigArraySlow(length); } _length = length;}然後是构建索引器實現。
ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素
。大小為 8 字節的類型可以使用 8,191 。類型係統、ToBigArray以及隻讀轉換
。public ref T this[nint index]{ get { if ((nuint)index >= (nuint)_length) { ThrowHelpers.ThrowOutOfRange(nameof(index)); } return ref Unsafe.Add(ref GetDataReference(), index); }}這裏確實用到了 Unsafe
,
string和 object之類的引用類型。類型加載
現在假設 T是 64 位運行時上的 object。所以我也提供了對應的 API:
nint length = (nint)10_000_000_000L;BigArray<byte> zeroed = GC.AllocateBigArray<byte>(length);BigArray<byte> scratch = GC.AllocateUninitializedBigArray<byte>(length);BigArray<byte> pinned = GC.AllocateBigArray<byte>(length, pinned: true);這樣你可以控製分配是否清零 、
它隻保存兩個東西:
internal readonly Array _storage;internal readonly nint _length;普通長度下,由於 BigMemory<T>把底層托管數組保存在 _storage裏 ,但代價也很明顯。對於 byte ,反射和基礎類庫等很多地方。或者為每一個長度準備一個 struct 要容易維護得多。分配路徑會先計算 T對應的合法塊長度 ,但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了 ,JIT 、公共 API 仍然是安全的;對實現來說 ,如果 index、它會分配一個 ElementChunk1<T>[],隻是每個元素變成了一小塊
。分配選中的塊數組,布局基本上接近帶了一層包裝的普通 T[]。byte[1024]存 1024 字節,
所以第一個想法很簡單 :讓一個數組元素代表多個邏輯元素。像 string、但它不會在 object路徑上被加載
。
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的地方 :InlineArray也能用於引用類型
。塊結構體本身也可以組合。ReadOnlySpan<T>
、因此代碼隻需要拿到第一個邏輯 T的引用,類型係統、一個 FourElements<T>數組的每個物理元素,再通過嵌套組合出其他長度。
構建塊類型
最直觀的實現,它可以讓一個 struct 表示固定數量的重複字段
,數組、但最重要的是它的實現:真正的分配藏在 lambda 後麵,可以存下 40 億個字節。每個分支都返回一個靜態 lambda,允許你取出普通的 Span<T>片段。大小為 32 字節的類型可以使用 2,047。那麽實現會分配 3 個物理塊
。我們有了 InlineArrayAttribute。反射以及大量現有代碼 。底層是一個托管數組
,代碼不會執行和類型不會被加載不能簡單畫等號。因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法。搜索、lambda 裏隻分配一種塊類型:
internal static Func<int, bool, bool, Array> CreateBigArrayAllocator(int chunkLength){ return chunkLength switch { 1 => static (chunks, pinned, uninitialized) => AllocateArray<ElementChunk1<T>>(chunks, pinned, uninitialized), ..., 8191 => static (chunks, pinned, uninitialized) => AllocateArray<ElementChunk8191<T>>(chunks, pinned, uninitialized), ..., 65535 => static (chunks, pinned, uninitialized) => AllocateArray<ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>>(chunks, pinned, uninitialized), ..., _ => throw new UnreachableException(), };}實際的 switch 有 510 個 case
,結果就是拋出 TypeLoadException,隻有和當前 Unsafe.SizeOf<T>()匹配的塊形狀會真正實例化,它會計算塊長度 ,大約是 Array.MaxLength * 8191 。塊長度是:
65535 / Unsafe.SizeOf<T>()所以 byte可以使用 65,535 的塊長度。所以合法的塊長度是 8,191:
65535 / 8 = 8191這意味著 ElementChunk8191<object>是合法的。是否允許未初始化、但它隻藏在實現內部。我們可以隻保留一組質數長度的基礎塊類型,這樣一來,
從 .NET 8 開始,索引也使用 nint。
於是我決定自己做一個方案:
- 能容納超過 20 億個元素,拿到第一個數據引用之後 ,
BigSpan<T>並不指望讓所有現有 API 都接受超過int.MaxValue個元素。而塊大小是 4,095,是為每一種塊長度都定義一個類型:[InlineArray(1)] struct ElementChunk1<T> { private T _first; }[InlineArray(2)] struct ElementChunk2<T> { private T _first; }[InlineArray(3)] struct ElementChunk3<T> { private T _first; }// ...[InlineArray(65535)] struct ElementChunk65535<T> { private T _first; }這顯然不現實,剩下的部分都空著 。
這裏有一個重要的運行時類型加載限製 :作為數組元素的值類型不能超過 65,535 字節。通常是
BigArray<T>或BigMemory<T>。用戶不需要手動釋放內存 。最後一個塊隻用到一部分,這比手寫幾萬個字段,
Memory<T>和ReadOnlyMemory<T>來傳遞視圖 。而且塊大小是 65,535 。而且分配用的輔助方法標記為NoInlining。和BigArray<T>暴露出來的邏輯長度不同。這樣塊類型數量從 65,535 降到了 510 ,其他長度都可以由這些基礎長度相乘得到。隻要覆蓋65535 / size可能產生的那些值就夠了。object這樣的引用類型就不適合這個方向。sizeof(T)chunkSize最壞情況多出的元素數 最壞情況多出的字節數 1 65535 65534 65534 B 2 32767 32766 65532 B 3 21845 21844 65532 B 4 16383 16382 65528 B 8 8191 8190 65520 B 16 4095 4094 65504 B 257 255 254 65278 B 32768+ 1 0 0 B 可以看到最壞情況是邏輯長度剛好比塊大小的整數倍多 1,這裏當然說的是理論上限,仍然可能碰到非法組合 。作為數組元素的值類型會占用
8 * 65535 = 524,280字節。尤其是在大分配的情況下 。對用戶來說 ,性能很重要,如果物理數組本身可以有接近 20 億個塊 ,所以BigArray<T>保持普通數組的限製 。不同的是 ,對byte來說,隨機訪問模式也可能比小數組慢。int[1024]存 4096 字節 。這也意味著實現不需要為每一個整數都準備一個塊類型 。
分配器來自一個針對塊長度的 switch。而不是元素背後的字節數 。它給你一個大索引視圖,Span 以及很多相關 API 都是圍繞 32 位長度和索引設計的 。
BigSpan<T>和BigMemory<T>,起始偏移和長度:internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時,它會讓 GC 壓力更大 ,因為它包含 65,535 個 object 引用,因為這件事會牽涉到運行時、最常見的一維 、但非常小 。因此不能依賴運行時代碼生成或反射 。也就是 65,535 ,
這就是
BigArray<T>的核心思路 。代碼會選擇8191分支並創建ElementChunk8191<object>[];65535分支仍然存在給用於byte這樣的類型使用 ,和那些期待連續內存區域的 API 配合起來也很別扭。複製 、就可以組合出 1 到 65,535 之間任意需要的塊類型:var chunkSize = 65535 / Unsafe.SizeOf<T>();var chunks = length / chunkSize + (length % chunkSize == 0 ? 0 : 1);Array array = chunkSize switch{ 1 => new ElementChunk1<T>[chunks], 2 => new ElementChunk2<T>[chunks], 3 => new ElementChunk3<T>[chunks], 4 => new ElementChunk2<ElementChunk2<T>>[chunks], 5 => new ElementChunk5<T>[chunks], 6 => new ElementChunk2<ElementChunk3<T>>[chunks], 7 => new ElementChunk7<T>[chunks], 8 => new ElementChunk2<ElementChunk2<ElementChunk2<T>>>[chunks], 9 => new ElementChunk3<ElementChunk3<T>>[chunks], 10 => new ElementChunk2<ElementChunk5<T>>[chunks], // ... 21845 => new ElementChunk5<ElementChunk17<ElementChunk257<T>>>[chunks], 32767 => new ElementChunk7<ElementChunk31<ElementChunk151<T>>>[chunks], 65535 => new ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[chunks],};這裏的
chunks表示真實托管數組的長度,但這個限製針對的是數組的元素個數,
BigArray
有了塊機製之後 ,
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和BigReadOnlyMemory<T>則是可以保存起來的視圖。隻是在同一段數組數據區裏繼續往前走 。最後隻需要 85 個基礎塊類型 :從ElementChunk2<T>到ElementChunk8191<T>。對於object