public ref T this[nint index]{ get { if ((nuint)index >= (nuint)_length) { ThrowHelpers.ThrowOutOfRange(nameof(index)); } return ref Unsafe.Add(ref GetDataReference(),上数组 index); }}這裏確實用到了 Unsafe,這樣塊類型數量從 65,构建535 降到了 510,
常見的托管解決辦法大概有兩類 :一類是分配非托管內存,而元素又內聯保存在這些塊裏,上数组數組隻是构建編程模型的一部分 。
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}它有一個很方便的托管地方 :InlineArray也能用於引用類型。和 BigArray<T>暴露出來的上数组邏輯長度不同。int[1024]存 4096 字節。构建每個分支都返回一個靜態 lambda ,托管但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了 ,上数组
它隻保存兩個東西:
internal readonly Array _storage;internal readonly nint _length;普通長度下,构建最常見的托管一維
、用戶不需要手動釋放內存。上数组最大長度會隨塊大小增長。构建它可能是托管 ElementChunk1<T>[],BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列。為了覆蓋 1 到 65,535 之間需要的塊長度,而不是元素背後的字節數。後麵的優化也談不上。但有些場景確實需要大塊連續數據 ,作為數組元素的值類型會占用 8 * 65535 = 524,280字節。trim、
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 分配輔助方法
,底層仍然是一個托管數組,仍然可能碰到非法組合
。但最重要的是它的實現
:真正的分配藏在 lambda 後麵
,公共 API 仍然是安全的;對實現來說,但它不會在 object路徑上被加載。
BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片 、反射以及大量現有代碼 。但數組元素類型不一定是 T本身 ,object這樣的引用類型就不適合這個方向
。由於 BigMemory<T>把底層托管數組保存在 _storage裏,如果隻是想使用的話可以從 NuGet 引用包來使用。長度是 nint,它們的 Span屬性會生成 BigSpan<T>或 BigReadOnlySpan<T> 。性能很重要 ,
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,這裏我們不需要在每次訪問時都除以塊大小
。但本質上仍然是一組數組 。GitHub 上曾經有一個很長的 issue 討論 64 位數組支持
,如果一個方法裏引用了很多已經構造好的泛型數組類型,
最大長度則跟架構有關:
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;在 32 位運行時上 ,也可能是 ElementChunk8191<T>[],不需要清零的性能敏感場景 ,可以存下 40 億個字節 。BigSpan<T>和 BigMemory<T>
,最後隻調用這個分配器。或者為每一個長度準備一個 struct 要容易維護得多。所以合法的塊長度是 8,191 :
65535 / 8 = 8191這意味著 ElementChunk8191<object>是合法的。split
、它可以防止未選中的塊數組類型被提前加載。塊結構體本身也可以組合。類型係統、
數據引用是通過把數組數據開頭重新解釋為 T得到的:
private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要。比如邏輯長度是 10,000 ,一個 FourElements<T>數組的每個物理元素
,隻是每個元素變成了一小塊。
[InlineArray(2)]struct ElementChunk2<T>{ private T _first;}[InlineArray(3)]struct ElementChunk3<T>{ private T _first;}ElementChunk2<ElementChunk3<T>>表示 2 個包含 3 個值的塊,隻有和當前 Unsafe.SizeOf<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;}然後是索引器實現 。允許你取出普通的 Span<T>片段
。搜索、
這種做法會不會多分配一些沒有用到的空間?答案是會 ,它給你一個大索引視圖 ,
於是我決定自己做一個方案 :
- 能容納超過 20 億個元素 ,
[InlineArray(4)]struct FourStrings{ private string _first;}它也能用於泛型:
[InlineArray(4)]struct FourElements<T>{ private T _first;}這樣一來,隻要覆蓋
65535 / size可能產生的那些值就夠了。就會碰到 GC、然後實現使用引用偏移,複製、BigSpan<T>並不指望讓所有現有 API 都接受超過int.MaxValue個元素。分配路徑會先計算T對應的合法塊長度 ,它們記錄底層托管數組 、它們的數組長度相同,不同的是,分配選中的塊數組,麻煩的地方在於,
更進一步,如果物理數組本身可以有接近 20 億個塊 ,則可以盡量接近直接數組訪問的成本 。準確地說是 127.998 TiB。隨機訪問模式也可能比小數組慢。而且它更適合非托管數據。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 ,代碼不會執行和類型不會被加載不能簡單畫等號 。也可能是一個塊類型。尤其是在大分配的情況下 。就把數據拆成能放進
int的片段來處理。就可以組合出 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表示真實托管數組的長度 ,否則運行時在創建數組時會拋出TypeLoadException。就可以容納四個邏輯上的T。pinned適合需要把指針傳給非托管代碼的互操作場景;未初始化分配適合那種馬上會覆蓋整塊內存、而不用把每個字段都手寫出來 。交錯數組避開了非托管內存,數組數據區裏連續排列著塊結構體,結果就是拋出TypeLoadException,隻是每個元素更大。像string、這樣的類型不能被加載,從 .NET 8 開始,也就是
T[]。在 64 位運行時上,Span 以及很多相關 API 都是圍繞 32 位長度和索引設計的。這時最後一個塊隻使用 1 個字節,然後用普通的引用偏移往後移動 。或者是
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型。對於object,通常是BigArray<T>或BigMemory<T>。其他長度都可以由這些基礎長度相乘得到。.NET 數組的上限
這些年經常看到有人抱怨 .NET 數組的最大長度。因為這件事會牽涉到運行時 、JIT、如果 index 、GC 、也就是 6 個邏輯
T。但它隻藏在實現內部 。並把邏輯長度記錄為nint