托管數在 組 上構建超大
T[] 。這時最後一個塊隻使用 1 個字節 ,托管Span 以及很多相關 API 都是上数组圍繞 32 位長度和索引設計的。它會計算塊長度 ,构建所以 BigArray<T>保持普通數組的托管限製
。BigArray<T>本身可以保持得很小。上数组這裏我們不需要在每次訪問時都除以塊大小。构建object這樣的托管引用類型就不適合這個方向。就可以組合出 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表示真實托管數組的長度,對用戶來說
,準確地說是 127.998 TiB。byte[1024]存 1024 字節 ,ToBigArray以及隻讀轉換 。如果 index 、
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和 BigReadOnlyMemory<T>則是可以保存起來的視圖
。隻是在同一段數組數據區裏繼續往前走。那麽四倍寬度的塊就能表示接近 80 億個邏輯元素。它可以讓一個 struct 表示固定數量的重複字段,一個 FourElements<T>數組的每個物理元素 ,如果一個方法裏引用了很多已經構造好的泛型數組類型,
有了這些塊類型之後
,對 byte來說,類型係統 、然後從 switch 裏拿到這個塊長度對應的分配器,Unsafe.Add(ref first, index)會移動 index個邏輯 T元素。而且它更適合非托管數據。最常見的一維 、像 string、對某個 T來說 ,機器仍然需要真的有足夠的內存。這樣一來,和 BigArray<T>暴露出來的邏輯長度不同。trim、分配路徑會先計算 T對應的合法塊長度,我們還會用 Span<T>、普通 .NET 代碼裏,並且在需要和現有 API 互操作時 ,它可以防止未選中的塊數組類型被提前加載。是為每一種塊長度都定義一個類型
:
[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; }這顯然不現實,而塊大小是 4,095,
它隻保存兩個東西 :
internal readonly Array _storage;internal readonly nint _length;普通長度下,但本質上仍然是一組數組。隻是每個元素變成了一小塊。
這就是 BigArray<T>的核心思路 。類型係統、而且對任意 T來說也不一定合法
。BigArray<T>另外記錄真實的邏輯長度,
基本思路
在 .NET 中,
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,代碼會選擇 8191分支並創建 ElementChunk8191<object>[];65535分支仍然存在給用於 byte這樣的類型使用 ,大約是 Array.MaxLength * 8191。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,
類型加載
現在假設 T是 64 位運行時上的 object
。通常是 BigArray<T>或 BigMemory<T>。
public ref T this[nint index]{ get { if ((nuint)index >= (nuint)_length) { ThrowHelpers.ThrowOutOfRange(nameof(index)); } return ref Unsafe.Add(ref GetDataReference(), index); }}這裏確實用到了 Unsafe,拿到第一個數據引用之後
,不同的是
,
但這個限製針對的是數組的元素個數
,它會分配一個 ElementChunk1<T>[],它仍然是一個托管數組對象 ,這裏當然說的是理論上限 ,那麽實現會分配 3 個物理塊 。隻是查看由別的對象保持存活的內存 ,如果連內存都分配不出來,int[1024]存 4096 字節。byte能使用的最大塊長度,而不是元素背後的字節數
。底層仍然是一個托管數組,
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;}然後是索引器實現。以及是否固定。
這比手寫幾萬個字段,起始偏移和長度 :
internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時,就把數據拆成能放進 int的片段來處理。集合 、同時仍然讓這段存儲對 GC 可見。
BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片 、
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,
在 64 位運行時上
,也就是 65,535
,大小為 8 字節的類型可以使用 8,191。最後隻需要 85 個基礎塊類型:從 ElementChunk2<T>到 ElementChunk8191<T>。因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法
。pinned適合需要把指針傳給非托管代碼的互操作場景;未初始化分配適合那種馬上會覆蓋整塊內存 、
最大長度則跟架構有關 :
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;在 32 位運行時上 ,可以寫成 :
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<byte>>>>因為 :
3 * 5 * 17 * 257 = 65535因此,
這也是為什麽 _storage的類型是 Array:實際運行時類型取決於 T 。更大的長度下,塊長度是:
65535 / Unsafe.SizeOf<T>()所以 byte可以使用 65,535 的塊長度
。JIT 和類型加載器在導入或編譯方法時,數組數據區裏連續排列著塊結構體
,再通過嵌套組合出其他長度
。但非常小。它會讓 GC 壓力更大,由於 BigMemory<T>把底層托管數組保存在 _storage裏 ,可以存下 40 億個字節 。length 或 slice 超出合法範圍 ,
nint offset = (nint)5_000_000_000L;Span<byte> window = buffer.AsSpan(offset, length: 4096);分配 API
最簡單的分配方式自然是調用構造函數 :
nint length = (nint)10_000_000_000L;BigArray<byte> buffer = new(length);不過 .NET 的數組也有顯式的 GC 分配輔助方法,
在 .NET 裏,因為這件事會牽涉到運行時
、它的長度受 int大小限製
。split 、如果隻是想使用的話可以從 NuGet 引用包來使用。搜索、它給你一個大索引視圖,公開 API 的輸入會先被驗證
,
BigSpan<T>是一個麵向超大連續區域的棧上視圖:
public readonly ref struct BigSpan<T>{ internal readonly ref T _first; internal readonly nint _length;}它的基本形狀和 Span<T>一樣:一個起始引用加一個長度 。剩下的部分都空著。
從 .NET 8 開始 ,
分配器來自一個針對塊長度的 switch。BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列。
BigSpan<T>並不指望讓所有現有 API 都接受超過 int.MaxValue個元素。真正的邏輯終點由 _length記錄。
寫在最後
有了 BigArray<T>、但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了 ,數組隻是編程模型的一部分 。而元素又內聯保存在這些塊裏
,隻要覆蓋 65535 / size可能產生的那些值就夠了。我們有了 InlineArrayAttribute。或者為每一個長度準備一個 struct 要容易維護得多。仍然可能碰到非法組合。ToArray、JIT 、會在到達這條路徑之前失敗。
通常不太建議隨意使用巨大的數組。比如邏輯長度是 10,000,所以合法的塊長度是 8,191 :
65535 / 8 = 8191這意味著 ElementChunk8191<object>是合法的 。
數據引用是通過把數組數據開頭重新解釋為 T得到的:
private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要。不需要清零的性能敏感場景
,也可能是一個塊類型 。分配選中的塊數組,跨過一個塊到下一個塊,nint本身無法表示更大的索引空間,它可能是 ElementChunk1<T>[] ,反射和基礎類庫等很多地方 。
構建塊類型
最直觀的實現,
[InlineArray(2)]struct ElementChunk2<T>{ private T _first;}[InlineArray(3)]struct ElementChunk3<T>{ private T _first;}ElementChunk2<ElementChunk3<T>>表示 2 個包含 3 個值的塊,
這種做法會不會多分配一些沒有用到的空間 ?答案是會,大小為 32 字節的類型可以使用 2,047。也就是 6 個邏輯 T。對於 byte
