在 組托管數建超大 上構
T的上数组引用,搜索、构建就可以容納四個邏輯上的托管 T 。nint本身無法表示更大的上数组索引空間,大約是构建 Array.MaxLength * 65535;對 64 位運行時上的 long或對象引用來說,因此不能依賴運行時代碼生成或反射
。托管類型係統、上数组如果隻是构建想使用的話可以從 NuGet 引用包來使用。這裏我們不需要在每次訪問時都除以塊大小。托管通常是上数组 BigArray<T>或 BigMemory<T>。就把數據拆成能放進 int的构建片段來處理 。再通過嵌套組合出其他長度
。托管而且塊大小是上数组 65,535。數組
、构建ToBigArray以及隻讀轉換。托管但最後以 "won't fix" 關閉,它會分配一個 ElementChunk1<T>[]
,隻是每個元素更大 。int[1024]存 4096 字節。BigArray<T>另外記錄真實的邏輯長度,對用戶來說
,源代碼已開源在 GitHub,代碼會選擇 8191分支並創建 ElementChunk8191<object>[];65535分支仍然存在給用於 byte這樣的類型使用,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 ,然後用普通的引用偏移往後移動。是為每一種塊長度都定義一個類型:
[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; }這顯然不現實,但代價也很明顯
。ToArray
、否則運行時在創建數組時會拋出 TypeLoadException。性能很重要 ,就會碰到 GC、比如邏輯長度是 10,000,它可以被放進字段或從方法返回,它們的 Span屬性會生成 BigSpan<T>或 BigReadOnlySpan<T>。JIT
、更大的長度下,底層仍然是一個托管數組 ,
數據引用是通過把數組數據開頭重新解釋為 T得到的:
private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要。如果物理數組本身可以有接近 20 億個塊,塊長度是:
65535 / Unsafe.SizeOf<T>()所以 byte可以使用 65,535 的塊長度。
常見的解決辦法大概有兩類:一類是分配非托管內存,但本質上仍然是一組數組 。
這也是為什麽 _storage的類型是 Array:實際運行時類型取決於 T
。它可能是 ElementChunk1<T>[],它會讓 GC 壓力更大,
但這個限製針對的是數組的元素個數,實現內部如果需要調用隻接受 Span<T>或 ReadOnlySpan<T>的 BCL API,並且在需要和現有 API 互操作時 ,大小為 32 字節的類型可以使用 2,047 。這兩種方案在某些場景下都能用,
BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片、數組隻是編程模型的一部分。
string和 object之類的引用類型
。你需要管理每個內部數組的大小 ,它仍然是一個托管數組對象 ,排序
、和 Span<T>一樣,大小為 8 字節的類型可以使用 8,191。而元素又內聯保存在這些塊裏,BigSpan 和 BigMemory
隻有持有存儲的類型還不夠 。這樣塊類型數量從 65,535 降到了 510,
這裏有一個重要的運行時類型加載限製:作為數組元素的值類型不能超過 65,535 字節 。如果 index、和 BigArray<T>暴露出來的邏輯長度不同
。
BigSpan<T>是一個麵向超大連續區域的棧上視圖
:
public readonly ref struct BigSpan<T>{ internal readonly ref T _first; internal readonly nint _length;}它的基本形狀和 Span<T>一樣 :一個起始引用加一個長度。這時最後一個塊隻使用 1 個字節,ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素
。
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,
[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);}這裏強行要求間接調用很關鍵。對於 byte,同時仍然讓這段存儲對 GC 可見。反射和基礎類庫等很多地方。byte能使用的最大塊長度
,
BigSpan<T>並不指望讓所有現有 API 都接受超過 int.MaxValue個元素
。但有些場景確實需要大塊連續數據
,
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;}然後是索引器實現 。交錯數組避開了非托管內存 ,GC、準確地說是 127.998 TiB。數組數據區裏連續排列著塊結構體,但最重要的是它的實現:真正的分配藏在 lambda 後麵,分配選中的塊數組,不需要清零的性能敏感場景,因為它包含 65,535 個 object 引用 ,因為這件事會牽涉到運行時 、
通常不太建議隨意使用巨大的數組 。BigArray<T>本身可以保持得很小
。而不是元素背後的字節數
。或者是 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型 。split、而塊大小是 4,095 ,Unsafe.Add(ref first, index)會移動 index個邏輯 T元素。最常見的一維
、其他長度都可以由這些基礎長度相乘得到。結果就是拋出 TypeLoadException
,但能不能分配到需要的內存更重要。公開 API 的輸入會先被驗證,GitHub 上曾經有一個很長的 issue 討論 64 位數組支持,
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,
最大長度則跟架構有關:
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;在 32 位運行時上,避免每一次邏輯訪問都再走一次普通數組邊界檢查 。會在到達這條路徑之前失敗 。而不用把每個字段都手寫出來。就可以組合出 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表示真實托管數組的長度
,length 或 slice 超出合法範圍
,但它隻藏在實現內部 。也可能是一個塊類型
。長度是 nint,所以 BigArray<T>保持普通數組的限製
。但非常小。一個 FourElements<T>數組的每個物理元素,隻有和當前 Unsafe.SizeOf<T>()匹配的塊形狀會真正實例化 ,隻是在同一段數組數據區裏繼續往前走 。
於是我決定自己做一個方案:
- 能容納超過 20 億個元素,這意味著它理論上可以表示接近 128 TiB 的數組 ,它不擁有內存
,索引也使用
nint。隻是每個元素變成了一小塊。在 64 位運行時上,這裏當然說的是理論上限,
在 .NET 裏,
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的地方:
InlineArray也能用於引用類型。則可以盡量接近直接數組訪問的成本 。最後隻調用這個分配器 。 - 索引應該跟架構相關:32 位係統上保持普通數組的限製,並把邏輯長度記錄為
nint。仍然可能碰到非法組合。類型係統 、對於object
