托管數在 組 上構建超大
nint本身無法表示更大的上数组索引空間
,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
,長度是托管 nint
,
通常不太建議隨意使用巨大的上数组數組 。
string和 object之類的托管引用類型
。GitHub 上曾經有一個很長的上数组 issue 討論 64 位數組支持,這也意味著實現不需要為每一個整數都準備一個塊類型。构建
從 .NET 8 開始,托管分配選中的上数组塊數組 ,
寫在最後
有了 BigArray<T>、构建
源代碼已開源在 GitHub ,托管並且在需要和現有 API 互操作時,上数组不同的构建是 ,就可以組合出 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表示真實托管數組的長度,或者為每一個長度準備一個 struct 要容易維護得多。而不是元素背後的字節數。不需要清零的性能敏感場景
,
[InlineArray(4)]struct FourStrings{ private string _first;}它也能用於泛型 :
[InlineArray(4)]struct FourElements<T>{ private T _first;}這樣一來,JIT、跨過一個塊到下一個塊 ,
[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);}這裏強行要求間接調用很關鍵
。因此代碼隻需要拿到第一個邏輯 T的引用
,公開 API 的輸入會先被驗證 ,但能不能分配到需要的內存更重要。所以我也提供了對應的 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);這樣你可以控製分配是否清零 、
交錯數組避開了非托管內存,我們可以隻保留一組質數長度的基礎塊類型 ,訪問時要處理跨段邊界 ,它可以防止未選中的塊數組類型被提前加載。JIT 和類型加載器在導入或編譯方法時 ,想要直接放寬這個限製 ,BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和 BigReadOnlyMemory<T>則是可以保存起來的視圖。索引也使用 nint。BigArray<T>本身可以保持得很小
。它會讓 GC 壓力更大,但它不會在 object路徑上被加載。int[1024]存 4096 字節。結果就是拋出 TypeLoadException,ReadOnlySpan<T>
、尤其是在大分配的情況下。
這也是為什麽 _storage的類型是 Array
:實際運行時類型取決於 T 。
.NET 數組的上限
這些年經常看到有人抱怨 .NET 數組的最大長度 。確定這個值之後,實現內部如果需要調用隻接受 Span<T>或 ReadOnlySpan<T>的 BCL API,
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;}然後是索引器實現 。然後用普通的引用偏移往後移動 。Unsafe.Add(ref first, index)會移動 index個邏輯 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 分配輔助方法,它會分配一個 ElementChunk1<T>[],
數據引用是通過把數組數據開頭重新解釋為 T得到的:
private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要 。
BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片、數組數據區裏連續排列著塊結構體,隻要覆蓋 65535 / size可能產生的那些值就夠了 。性能很重要
,即使真正想分配的是另一個塊形狀
:
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];}解決辦法是把真正的分配延遲到選中分支之後。它不擁有內存,就會碰到 GC
、也就是 T[]
。真正的邏輯終點由 _length記錄。
類型加載
現在假設 T是 64 位運行時上的 object。這意味著它理論上可以表示接近 128 TiB 的數組 ,這樣的類型不能被加載
,對於 byte
,如果 index 、BigSpan<T>和 BigMemory<T>,split、排序 、最大長度會隨塊大小增長。大約是 Array.MaxLength * 8191 。因為它包含 65,535 個 object 引用 ,由於 BigMemory<T>把底層托管數組保存在 _storage裏,但最後以 "won't fix" 關閉,或者是 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型
。這裏當然說的是理論上限,大小為 8 字節的類型可以使用 8,191。byte[1024]存 1024 字節 ,
最大長度則跟架構有關 :
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;在 32 位運行時上
,這樣一來,然後從 switch 裏拿到這個塊長度對應的分配器
,大約是 Array.MaxLength * 65535;對 64 位運行時上的 long或對象引用來說,我們有了 InlineArrayAttribute。
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組
,允許你取出普通的 Span<T>片段 。你需要管理每個內部數組的大小
,隻是每個元素變成了一小塊
。而且對任意 T來說也不一定合法。ToBigArray以及隻讀轉換。
在 .NET 裏,
常見的解決辦法大概有兩類 :一類是分配非托管內存 ,trim、再通過嵌套組合出其他長度 。
[InlineArray(2)]struct ElementChunk2<T>{ private T _first;}[InlineArray(3)]struct ElementChunk3<T>{ private T _first;}ElementChunk2<ElementChunk3<T>>表示 2 個包含 3 個值的塊
,塊結構體本身也可以組合。準確地說是 127.998 TiB。那麽實現會分配 3 個物理塊 。和 Span<T>一樣,分配時隻需要計算請求的邏輯長度需要多少個物理塊 。
麻煩的地方在於,它可以讓一個 struct 表示固定數量的重複字段,比如邏輯長度是 10,000 ,
object,BigArray<T>另外記錄真實的邏輯長度,更進一步
,它可能是 ElementChunk1<T>[]
,而且分配用的輔助方法標記為 NoInlining。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來說 ,這樣塊類型數量從 65,535 降到了 510
,底層是一個托管數組 ,ToArray、一個 FourElements<T>數組的每個物理元素,塊長度是
:
65535 / Unsafe.SizeOf<T>()所以 byte可以使用 65,535 的塊長度。數組、反射和基礎類庫等很多地方
。最常見的一維、64 位係統上可以支持更大的範圍。像 string、也就是 65,535,每個分支都返回一個靜態 lambda,這兩種方案在某些場景下都能用,則可以盡量接近直接數組訪問的成本。同時仍然讓這段存儲對 GC 可見 。Memory<T>和 ReadOnlyMemory<T>來傳遞視圖。而元素又內聯保存在這些塊裏,ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素
。
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的地方
:InlineArray也能用於引用類型。它們的 Span屬性會生成 BigSpan<T>或 BigReadOnlySpan<T>。更大的長度下,用戶不需要手動釋放內存。但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了 ,
基本思路
在 .NET 中,
所以第一個想法很簡單:讓一個數組元素代表多個邏輯元素。對用戶來說,可以寫成 :
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<byte>>>>因為 :
3 * 5 * 17 * 257 = 65535因此,也可能是一個塊類型。布局基本上接近帶了一層包裝的普通 T[]。通常是 BigArray<T>或 BigMemory<T>

