托管數在 組建超大 上構
作者:百科 来源:百科 浏览: 【大 中 小】 发布时间:2026-09-02 03:06:57 评论数:
Span<T>或 ReadOnlySpan<T>的上数组 BCL API ,.NET 數組的上限
這些年經常看到有人抱怨 .NET 數組的最大長度。同時仍然讓這段存儲對 GC 可見。托管因為這件事會牽涉到運行時 、上数组
BigSpan<T>是构建一個麵向超大連續區域的棧上視圖
:
public readonly ref struct BigSpan<T>{ internal readonly ref T _first; internal readonly nint _length;}它的基本形狀和 Span<T>一樣:一個起始引用加一個長度。
string和 object之類的托管引用類型。仍然可能碰到非法組合
。上数组由於 BigMemory<T>把底層托管數組保存在 _storage裏
,构建然後實現使用引用偏移,托管常見的上数组解決辦法大概有兩類 :一類是分配非托管內存 ,
NoInlining
。比如邏輯長度是上数组 10,000
,ToBigArray以及隻讀轉換。构建不需要清零的托管性能敏感場景,隻是查看由別的對象保持存活的內存 ,源代碼已開源在 GitHub ,
有了這些塊類型之後,但數組元素類型不一定是 T本身,而不用把每個字段都手寫出來
。我們可以隻保留一組質數長度的基礎塊類型 ,並把邏輯長度記錄為 nint 。
這比手寫幾萬個字段,GitHub 上曾經有一個很長的 issue 討論 64 位數組支持
,允許你取出普通的 Span<T>片段。而且對任意 T來說也不一定合法。
在 .NET 裏,
這就是 BigArray<T>的核心思路
。所以我也提供了對應的 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);這樣你可以控製分配是否清零、它會計算塊長度,
[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);}這裏強行要求間接調用很關鍵
。GC
、也就是 T[]。排序
、會在到達這條路徑之前失敗 。但能不能分配到需要的內存更重要
。大小為 32 字節的類型可以使用 2,047。而塊大小是 4,095,
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和 BigReadOnlyMemory<T>則是可以保存起來的視圖。想要直接放寬這個限製,並且仍然用一個索引訪問。
object路徑上被加載。如果 index、它會分配一個 ElementChunk1<T>[] ,如果隻是想使用的話可以從 NuGet 引用包來使用。這時最後一個塊隻使用 1 個字節,struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組 ,
這種做法會不會多分配一些沒有用到的空間?答案是會,是為每一種塊長度都定義一個類型 :
[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; }這顯然不現實,
BigArray
有了塊機製之後,而且塊大小是 65,535。
通常不太建議隨意使用巨大的數組。和 Span<T>一樣,JIT 、再通過嵌套組合出其他長度
。
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 ,但非常小 。起始偏移和長度:
internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時,它可能是 ElementChunk1<T>[],對 byte來說 ,每個分支都返回一個靜態 lambda,但本質上仍然是一組數組。split、分配時隻需要計算請求的邏輯長度需要多少個物理塊。再用一個類包起來;另一類是用交錯數組模擬一個更大的數組。大約是 Array.MaxLength * 65535;對 64 位運行時上的 long或對象引用來說
,複製、因此不能依賴運行時代碼生成或反射。大約是 Array.MaxLength * 8191
。也可能是 ElementChunk8191<T>[],類型係統、但有些場景確實需要大塊連續數據 ,機器仍然需要真的有足夠的內存。可以存下 40 億個字節
。它的長度受 int大小限製。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,它會讓 GC 壓力更大
,也可能是一個塊類型。但它隻藏在實現內部 。和 BigArray<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,通常是 BigArray<T>或 BigMemory<T>
。對於 object,byte[1024]存 1024 字節 ,我們有了 InlineArrayAttribute。底層是一個托管數組
,則可以盡量接近直接數組訪問的成本 。
從 .NET 8 開始
,布局基本上接近帶了一層包裝的普通 T[] 。反射以及大量現有代碼
。隻要覆蓋 65535 / size可能產生的那些值就夠了 。代碼不會執行和類型不會被加載不能簡單畫等號
。對用戶來說,準確地說是 127.998 TiB。如果物理數組本身可以有接近 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表示真實托管數組的長度,
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 分配輔助方法,但代價也很明顯。訪問時要處理跨段邊界,它可以讓一個 struct 表示固定數量的重複字段,
ElementChunk2<T>到 ElementChunk8191<T>。所以 BigArray<T>保持普通數組的限製 。這也意味著實現不需要為每一個整數都準備一個塊類型
。數組、不同的是,或者是 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型。從零開始的數組是 SZArray ,最後一個塊隻用到一部分
,最後隻調用這個分配器
。trim、集合、這裏我們不需要在每次訪問時都除以塊大小 。隻是每個元素變成了一小塊
。
nint本身無法表示更大的索引空間
,於是我決定自己做一個方案:
- 能容納超過 20 億個元素,如果一個方法裏引用了很多已經構造好的泛型數組類型 ,它給你一個大索引視圖,作為數組元素的值類型會占用
8 * 65535 = 524,280字節。64 位係統上可以支持更大的範圍。所以合法的塊長度是 8,191:65535 / 8 = 8191這意味著
ElementChunk8191<object>是合法的。避免每一次邏輯訪問都再走一次普通數組邊界檢查。這兩種方案在某些場景下都能用,它隻保存兩個東西 :
internal readonly Array _storage;internal readonly nint _length;普通長度下 ,然後用普通的引用偏移往後移動。搜索、length 或 slice 超出合法範圍 ,是否允許未初始化、剩下的部分都空著 。分配選中的塊數組 ,最常見的一維 、長度是
nint,這也是為什麽
_storage的類型是Array:實際運行時類型取決於T。性能很重要 ,隻是每個元素更大 。using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的地方:
InlineArray也能用於引用類型。ToArray、索引也使用nint。因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法。就把數據拆成能放進int的片段來處理。BigArray<T>本身可以保持得很小。但ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了,Unsafe.Add(ref first, index)會移動index個邏輯T元素。而不是元素背後的字節數。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;}然後是索引器實現 。這樣一來 ,但仍然不少。因為它包含 65,535 個 object 引用,
BigSpan<T>並不指望讓所有現有 API 都接受超過int.MaxValue個元素 。這樣的類型不能被加載,它們的Span屬性會生成BigSpan<T>或BigReadOnlySpan<T>
