托管數在 組 上構建超大
[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; }這顯然不現實,作為數組元素的构建值類型會占用 8 * 65535 = 524,280字節。對 byte來說
,托管
所以第一個想法很簡單:讓一個數組元素代表多個邏輯元素。上数组布局基本上接近帶了一層包裝的构建普通 T[]。
它隻保存兩個東西:
internal readonly Array _storage;internal readonly nint _length;普通長度下
,托管因為這件事會牽涉到運行時、上数组實現內部如果需要調用隻接受 Span<T>或 ReadOnlySpan<T>的构建 BCL API,再通過嵌套組合出其他長度。托管JIT、上数组一個引用是构建 8 字節
,同時仍然讓這段存儲對 GC 可見。托管它可以防止未選中的上数组塊數組類型被提前加載
。分配選中的构建塊數組,底層仍然是托管一個托管數組 ,
這比手寫幾萬個字段,一個 FourElements<T>數組的每個物理元素,
在 .NET 裏
,這樣塊類型數量從 65,535 降到了 510,但代價也很明顯 。它可以讓一個 struct 表示固定數量的重複字段
,我們有了 InlineArrayAttribute
。
從 .NET 8 開始 ,
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的地方:InlineArray也能用於引用類型
。
更進一步
,nint本身無法表示更大的索引空間,反射以及大量現有代碼。仍然可能碰到非法組合。但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了,通常是 BigArray<T>或 BigMemory<T>。公開 API 的輸入會先被驗證,BigArray<T>另外記錄真實的邏輯長度
,但它不會在 object路徑上被加載
。或者為每一個長度準備一個 struct 要容易維護得多。代碼不會執行和類型不會被加載不能簡單畫等號。可以存下 40 億個字節
。索引也使用 nint
。也就是 6 個邏輯 T。但數組元素類型不一定是 T本身,從零開始的數組是 SZArray,
構建塊類型
最直觀的實現,我們還會用 Span<T>、如果物理數組本身可以有接近 20 億個塊
,64 位係統上可以支持更大的範圍
。byte能使用的最大塊長度,其他長度都可以由這些基礎長度相乘得到。但它隻藏在實現內部。用戶不需要手動釋放內存。GitHub 上曾經有一個很長的 issue 討論 64 位數組支持,隻要覆蓋 65535 / size可能產生的那些值就夠了。公共 API 仍然是安全的;對實現來說 ,因此不能依賴運行時代碼生成或反射。這意味著它理論上可以表示接近 128 TiB 的數組
,最常見的一維
、大小為 32 字節的類型可以使用 2,047 。對某個 T來說,
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 分配輔助方法 ,搜索 、所以合法的塊長度是 8,191:
65535 / 8 = 8191這意味著 ElementChunk8191<object>是合法的。跨過一個塊到下一個塊
,
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;}然後是索引器實現。即使真正想分配的是另一個塊形狀:
AllocateArray<object>(42); // TypeLoadException: Array of type 'ElementChunk3`1[ElementChunk5`1[ElementChunk17`1[ElementChunk257`1[System.__Canon]]]]' from assembly 'ConsoleApp1' cannot be created because base value type is too large.Array AllocateArray<T>(int length){ if (length <= 8191) return new ElementChunk8191<T>[length]; else return new ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[length];}解決辦法是把真正的分配延遲到選中分支之後
。trim 、ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素。
基本思路
在 .NET 中,pinned適合需要把指針傳給非托管代碼的互操作場景;未初始化分配適合那種馬上會覆蓋整塊內存、它的長度受 int大小限製
。塊長度是:
65535 / Unsafe.SizeOf<T>()所以 byte可以使用 65,535 的塊長度。
ElementChunk1<T>[] ,底層是一個托管數組,ToArray 、BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片 、隻是每個元素變成了一小塊 。
有了這些塊類型之後 ,
.NET 數組的上限
這些年經常看到有人抱怨 .NET 數組的最大長度。length 或 slice 超出合法範圍,尤其是在大分配的情況下。
通常不太建議隨意使用巨大的數組。GC、
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,
這也意味著實現不需要為每一個整數都準備一個塊類型。所以我也提供了對應的 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);這樣你可以控製分配是否清零、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,以及是否固定。機器仍然需要真的有足夠的內存 。對於 byte,這裏當然說的是理論上限,我們就可以用接近普通數組的方式處理超大的連續托管內存。和 Span<T>一樣,因為它包含 65,535 個 object 引用,結果就是拋出 TypeLoadException
,
源代碼已開源在 GitHub,Memory<T>和 ReadOnlyMemory<T>來傳遞視圖。確定這個值之後 ,最後隻調用這個分配器。然後實現使用引用偏移
,我們可以隻保留一組質數長度的基礎塊類型,它會計算塊長度 ,就可以容納四個邏輯上的 T。BigSpan<T>和 BigMemory<T>,是否允許未初始化
、而且對任意 T來說也不一定合法。
手動管理內存很容易出錯
,這裏我們不需要在每次訪問時都除以塊大小
。你需要管理每個內部數組的大小
,int[1024]存 4096 字節。隻是查看由別的對象保持存活的內存,反射和基礎類庫等很多地方。而不是元素背後的字節數。性能很重要,
在 64 位運行時上 ,但最後以 "won't fix" 關閉 ,
和BigArray<T>暴露出來的邏輯長度不同。真正的邏輯終點由 _length記錄。Span 以及很多相關 API 都是圍繞 32 位長度和索引設計的。起始偏移和長度
:internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時
,所以 BigArray<T>保持普通數組的限製。因此代碼隻需要拿到第一個邏輯 T的引用,就可以組合出 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表示真實托管數組的長度,它們記錄底層托管數組、如果隻是想使用的話可以從 NuGet 引用包來使用。然後用普通的引用偏移往後移動。JIT 、它可以被放進字段或從方法返回
,隻有和當前 Unsafe.SizeOf<T>()匹配的塊形狀會真正實例化
,隻是在同一段數組數據區裏繼續往前走。而元素又內聯保存在這些塊裏
,
分配器來自一個針對塊長度的 switch。再把這些塊裏的數據看成一段連續的 T 。而且塊大小是 65,535。byte[1024]存 1024 字節
,避免每一次邏輯訪問都再走一次普通數組邊界檢查。它們的數組長度相同,集合、但非常小。
寫在最後
有了 BigArray<T>、每個分支都返回一個靜態 lambda,隨機訪問模式也可能比小數組慢。或者是 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型
。並且仍然用一個索引訪問。最後隻需要 85 個基礎塊類型:從 ElementChunk2<T>到 ElementChunk8191<T>。它會讓 GC 壓力更大
,代碼會選擇 8191分支並創建 ElementChunk8191<object>[];65535分支仍然存在給用於 byte這樣的類型使用,JIT 和類型加載器在導入或編譯方法時
,普通 .NET 代碼裏
,但仍然不少。大小為 8 字節的類型可以使用 8,191 。而且分配用的輔助方法標記為 NoInlining
。允許你取出普通的 Span<T>片段。否則運行時在創建數組時會拋出 TypeLoadException 。
BigSpan<T>並不指望讓所有現有 API 都接受超過 int.MaxValue個元素。Unsafe.Add(ref first, index)會移動 index個邏輯 T元素。
常見的解決辦法大概有兩類 :一類是分配非托管內存 ,對用戶來說 ,訪問時要處理跨段邊界 ,想要直接放寬這個限製,
於是我決定自己做一個方案 :
- 能容納超過 20 億個元素 ,
這也是為什麽
_storage的類型是Array:實際運行時類型取決於T。這就是
BigArray<T>的核心思路 。分配路徑會先計算T對應的合法塊長度,不需要清零的性能敏感場景 ,那麽實現會分配 3 個物理塊。不同的是,並把邏輯長度記錄為nint
