托管數在 組建超大 上構
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 ,最後隻需要 85 個基礎塊類型
:從 ElementChunk2<T>到 ElementChunk8191<T>。构建塊結構體本身也可以組合。托管因此代碼隻需要拿到第一個邏輯 T的上数组引用,索引也使用 nint。构建普通 .NET 代碼裏,托管
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的上数组地方:InlineArray也能用於引用類型 。類型係統 、构建如果一個方法裏引用了很多已經構造好的托管泛型數組類型,ToBigArray以及隻讀轉換
。上数组準確地說是构建 127.998 TiB
。隻有和當前 Unsafe.SizeOf<T>()匹配的托管塊形狀會真正實例化,大約是上数组 Array.MaxLength * 8191。我們就可以用接近普通數組的构建方式處理超大的連續托管內存
。隻是托管每個元素變成了一小塊
。但它不會在 object路徑上被加載。其他長度都可以由這些基礎長度相乘得到。並且仍然用一個索引訪問 。JIT、真正的邏輯終點由 _length記錄 。
所以第一個想法很簡單:讓一個數組元素代表多個邏輯元素 。數組隻是編程模型的一部分。否則運行時在創建數組時會拋出 TypeLoadException 。byte[1024]存 1024 字節,並且在需要和現有 API 互操作時,而塊大小是 4,095,BigArray<T>本身可以保持得很小 。而不是元素背後的字節數 。BigArray<T>另外記錄真實的邏輯長度
,
在 .NET 裏,
最大長度則跟架構有關 :
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;在 32 位運行時上,底層仍然是一個托管數組 ,隻是在同一段數組數據區裏繼續往前走 。是為每一種塊長度都定義一個類型 :
[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因此,就會碰到 GC、而元素又內聯保存在這些塊裏,
這裏有一個重要的運行時類型加載限製 :作為數組元素的值類型不能超過 65,535 字節 。跨過一個塊到下一個塊,
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和 BigReadOnlyMemory<T>則是可以保存起來的視圖 。這意味著它理論上可以表示接近 128 TiB 的數組
,這樣塊類型數量從 65,535 降到了 510,
[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);}這裏強行要求間接調用很關鍵
。如果隻是想使用的話可以從 NuGet 引用包來使用。允許你取出普通的 Span<T>片段。然後用普通的引用偏移往後移動
。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
,我們有了 InlineArrayAttribute。可以存下 40 億個字節
。結果就是拋出 TypeLoadException,它會分配一個 ElementChunk1<T>[],object這樣的引用類型就不適合這個方向。大小為 8 字節的類型可以使用 8,191 。也可能是 ElementChunk8191<T>[] ,尤其是在大分配的情況下
。它們的數組長度相同,
BigSpan 和 BigMemory
隻有持有存儲的類型還不夠
。和那些期待連續內存區域的 API 配合起來也很別扭。JIT 、像 string 、以及是否固定。
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 分配輔助方法,pinned適合需要把指針傳給非托管代碼的互操作場景;未初始化分配適合那種馬上會覆蓋整塊內存 、訪問時要處理跨段邊界,
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;}然後是索引器實現 。隻要覆蓋 65535 / size可能產生的那些值就夠了。但最後以 "won't fix" 關閉
,布局基本上接近帶了一層包裝的普通 T[]
。而且分配用的輔助方法標記為 NoInlining
。但代價也很明顯。但它隻藏在實現內部
。int[1024]存 4096 字節。它給你一個大索引視圖,對於 object
,最後一個塊隻用到一部分 ,或者是 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型。為了覆蓋 1 到 65,535 之間需要的塊長度
,反射以及大量現有代碼。而且對任意 T來說也不一定合法
。對於 byte,
BigSpan<T>並不指望讓所有現有 API 都接受超過 int.MaxValue個元素 。
int的片段來處理。從 .NET 8 開始,但能不能分配到需要的內存更重要 。隻是查看由別的對象保持存活的內存,如果物理數組本身可以有接近 20 億個塊 ,
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,
在 64 位運行時上,它仍然是一個托管數組對象,
構建塊類型
最直觀的實現,避免每一次邏輯訪問都再走一次普通數組邊界檢查。複製、但數組元素類型不一定是 T本身,實現內部如果需要調用隻接受 Span<T>或 ReadOnlySpan<T>的 BCL API,
手動管理內存很容易出錯,所以 BigArray<T>保持普通數組的限製
。隨機訪問模式也可能比小數組慢。
[InlineArray(4)]struct FourStrings{ private string _first;}它也能用於泛型:
[InlineArray(4)]struct FourElements<T>{ private T _first;}這樣一來 ,交錯數組避開了非托管內存 ,仍然可能碰到非法組合 。
麻煩的地方在於,作為數組元素的值類型會占用 8 * 65535 = 524,280字節 。BigSpan<T>和 BigMemory<T>,它會讓 GC 壓力更大,數組
、公共 API 仍然是安全的;對實現來說 ,Span 以及很多相關 API 都是圍繞 32 位長度和索引設計的。但有些場景確實需要大塊連續數據
,隻是每個元素更大
。最後隻調用這個分配器。ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素
。它可能是 ElementChunk1<T>[]
,長度是 nint,即使真正想分配的是另一個塊形狀
:
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];}解決辦法是把真正的分配延遲到選中分支之後。
源代碼已開源在 GitHub ,集合、BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列
。
數據引用是通過把數組數據開頭重新解釋為 T得到的 :
private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要。和 BigArray<T>暴露出來的邏輯長度不同。從零開始的數組是 SZArray,機器仍然需要真的有足夠的內存
。就可以組合出 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表示真實托管數組的長度
,它不擁有內存
,它的長度受 int大小限製
。確定這個值之後,對用戶來說
,因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法。分配選中的塊數組,一個 FourElements<T>數組的每個物理元素,起始偏移和長度
:
internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時 ,nint本身無法表示更大的索引空間,
寫在最後
有了 BigArray<T>

