T對應的构建合法塊長度 ,則可以盡量接近直接數組訪問的托管成本。更大的上数组長度下,大約是构建 Array.MaxLength * 8191。準確地說是托管 127.998 TiB。而元素又內聯保存在這些塊裏,上数组但仍然不少。构建ToBigArray以及隻讀轉換 。托管[MethodImpl(MethodImplOptions.NoInlining)]private static Array AllocateArray<TElement>(int chunks,上数组 bool pinned, bool uninitialized){ return uninitialized ? GC.AllocateUninitializedArray<TElement>(chunks, pinned) : GC.AllocateArray<TElement>(chunks, pinned);}這裏強行要求間接調用很關鍵 。
object這樣的上数组引用類型就不適合這個方向
。交錯數組避開了非托管內存,构建而且它更適合非托管數據 。托管於是我決定自己做一個方案 :
- 能容納超過 20 億個元素,
它隻保存兩個東西 :
internal readonly Array _storage;internal readonly nint _length;普通長度下,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,真正的邏輯終點由
_length記錄。因為它包含 65,535 個 object 引用,常見的解決辦法大概有兩類 :一類是分配非托管內存 ,我們還會用
Span<T>、想要直接放寬這個限製,最後一個塊隻用到一部分,由於BigMemory<T>把底層托管數組保存在_storage裏 ,trim、會在到達這條路徑之前失敗 。但本質上仍然是一組數組 。分配器來自一個針對塊長度的 switch 。對於
byte,或者是ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型 。公開 API 的輸入會先被驗證 ,BigArray<T>本身可以保持得很小 。布局基本上接近帶了一層包裝的普通T[]。這意味著它理論上可以表示接近 128 TiB 的數組,這也意味著實現不需要為每一個整數都準備一個塊類型。避免每一次邏輯訪問都再走一次普通數組邊界檢查。它可以讓一個 struct 表示固定數量的重複字段,反射和基礎類庫等很多地方 。
int[1024]存 4096 字節。可以存下 40 億個字節。最大長度會隨塊大小增長 。也可能是一個塊類型。length 或 slice 超出合法範圍,JIT 、也可能是ElementChunk8191<T>[],但有些場景確實需要大塊連續數據,Span 以及很多相關 API 都是圍繞 32 位長度和索引設計的 。同時仍然讓這段存儲對 GC 可見。有了這些塊類型之後 ,為了覆蓋 1 到 65,535 之間需要的塊長度 ,從零開始的數組是 SZArray ,排序、否則運行時在創建數組時會拋出
TypeLoadException。結果就是拋出TypeLoadException,這裏當然說的是理論上限,底層仍然是一個托管數組 ,隻是在同一段數組數據區裏繼續往前走 。大約是Array.MaxLength * 65535;對 64 位運行時上的long或對象引用來說 ,或者為每一個長度準備一個 struct 要容易維護得多。代碼會選擇8191分支並創建ElementChunk8191<object>[];65535分支仍然存在給用於byte這樣的類型使用,它給你一個大索引視圖,它可以被放進字段或從方法返回,就可以容納四個邏輯上的T。通常是BigArray<T>或BigMemory<T>。但數組元素類型不一定是T本身,在 64 位運行時上 ,數組、如果物理數組本身可以有接近 20 億個塊 ,就可以組合出 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表示真實托管數組的長度,而且對任意T來說也不一定合法。所以第一個想法很簡單 :讓一個數組元素代表多個邏輯元素 。對用戶來說,而且塊大小是 65,535。性能很重要,再用一個類包起來;另一類是用交錯數組模擬一個更大的數組。它會計算塊長度 ,如果一個方法裏引用了很多已經構造好的泛型數組類型,隻有和當前
Unsafe.SizeOf<T>()匹配的塊形狀會真正實例化 ,在 .NET 裏,代碼不會執行和類型不會被加載不能簡單畫等號 。就把數據拆成能放進
int的片段來處理 。這時最後一個塊隻使用 1 個字節 ,這裏我們不需要在每次訪問時都除以塊大小。剩下的部分都空著 。BigArray<T>另外記錄真實的邏輯長度 ,作為數組元素的值類型會占用8 * 65535 = 524,280字節 。我們可以隻保留一組質數長度的基礎塊類型,並且在需要和現有 API 互操作時,手動管理內存很容易出錯,
這就是
BigArray<T>的核心思路 。尤其是在大分配的情況下。隻要覆蓋65535 / size可能產生的那些值就夠了 。它可以防止未選中的塊數組類型被提前加載 。JIT、也就是 6 個邏輯T。用戶不需要手動釋放內存。索引也使用nint。
基本思路
在 .NET 中 ,它會讓 GC 壓力更大
,它們的 Span屬性會生成 BigSpan<T>或 BigReadOnlySpan<T>。BigSpan<T>和 BigMemory<T>,集合 、就會碰到 GC
、和那些期待連續內存區域的 API 配合起來也很別扭。不需要清零的性能敏感場景
,類型係統、nint本身無法表示更大的索引空間,但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了,ToArray、是為每一種塊長度都定義一個類型:
[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; }這顯然不現實 ,可以寫成:
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<byte>>>>因為 :
3 * 5 * 17 * 257 = 65535因此 ,仍然可能碰到非法組合。
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的地方:InlineArray也能用於引用類型。
string和 object之類的引用類型
。和 BigArray<T>暴露出來的邏輯長度不同。BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片、
BigSpan 和 BigMemory
隻有持有存儲的類型還不夠。起始偏移和長度:
internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時,
.NET 數組的上限
這些年經常看到有人抱怨 .NET 數組的最大長度。以及是否固定。而塊大小是 4,095,
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;}然後是索引器實現
。普通 .NET 代碼裏
,你需要管理每個內部數組的大小
,實現內部如果需要調用隻接受 Span<T>或 ReadOnlySpan<T>的 BCL API,隻是每個元素更大
。塊結構體本身也可以組合。
BigSpan<T>是一個麵向超大連續區域的棧上視圖
:
public readonly ref struct BigSpan<T>{ internal readonly ref T _first; internal readonly nint _length;}它的基本形狀和 Span<T>一樣
:一個起始引用加一個長度。
但這個限製針對的是數組的元素個數,對於 object,大小為 8 字節的類型可以使用 8,191。GC、一個 FourElements<T>數組的每個物理元素
,塊長度是:
65535 / Unsafe.SizeOf<T>()所以 byte可以使用 65,535 的塊長度。
構建塊類型
最直觀的實現 ,但能不能分配到需要的內存更重要。ReadOnlySpan<T> 、它的長度受 int大小限製
。
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,因此不能依賴運行時代碼生成或反射。數組隻是編程模型的一部分 。如果連內存都分配不出來,隨機訪問模式也可能比小數組慢 。長度是 nint,
public ref T this[nint index]{ get { if ((nuint)index >= (nuint)_length) { ThrowHelpers.ThrowOutOfRange(nameof(index)); } return ref Unsafe.Add(ref GetDataReference(), index); }}這裏確實用到了 Unsafe
,那麽四倍寬度的塊就能表示接近 80 億個邏輯元素 。即使真正想分配的是另一個塊形狀:
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];}解決辦法是把真正的分配延遲到選中分支之後 。
更進一步,
這也是為什麽 _storage的類型是 Array :實際運行時類型取決於 T。
源代碼已開源在 GitHub ,所以我也提供了對應的 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);這樣你可以控製分配是否清零、複製 、然後從 switch 裏拿到這個塊長度對應的分配器 ,
從 .NET 8 開始,
最大長度則跟架構有關 :
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;在 32 位運行時上
,但它隻藏在實現內部。因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法
。但最後以 "won't fix" 關閉,我們就可以用接近普通數組的方式處理超大的連續托管內存
。它們記錄底層托管數組、機器仍然需要真的有足夠的內存
。ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素。因此代碼隻需要拿到第一個邏輯 T的引用
,訪問時要處理跨段邊界
,隻是每個元素變成了一小塊
。確定這個值之後,但它不會在 object路徑上被加載 。分配時隻需要計算請求的邏輯長度需要多少個物理塊。跨過一個塊到下一個塊
,
這裏有一個重要的運行時類型加載限製:作為數組元素的值類型不能超過 65,535 字節。但代價也很明顯 。BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列 。每個分支都返回一個靜態 lambda
,
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和 BigReadOnlyMemory<T>則是可以保存起來的視圖。split 、拿到第一個數據引用之後,一個引用是 8 字節,我們有了 InlineArrayAttribute