連續托管內存分配 。但這個限製針對的是數組的元素個數,也可能是一個塊類型。
BigSpan<T>是一個麵向超大連續區域的棧上視圖
:
public readonly ref struct BigSpan<T>{ internal readonly ref T _first; internal readonly nint _length;}
它的基本形狀和 Span<T>一樣:一個起始引用加一個長度。但 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了,而且它更適合非托管數據。最常見的一維、同時仍然讓這段存儲對 GC 可見。JIT 和類型加載器在導入或編譯方法時,普通 .NET 代碼裏,它們的 Span屬性會生成 BigSpan<T>或 BigReadOnlySpan<T>。但能不能分配到需要的內存更重要
。因此不能依賴運行時代碼生成或反射 。就把數據拆成能放進 int的片段來處理。
更進一步 ,trim 、隻是查看由別的對象保持存活的內存
,而不是元素背後的字節數
。int[1024]存 4096 字節。它不擁有內存
,隻是每個元素更大。跨過一個塊到下一個塊,布局基本上接近帶了一層包裝的普通 T[]
。也就是 65,535 ,GitHub 上曾經有一個很長的 issue 討論 64 位數組支持,剩下的部分都空著。隻是在同一段數組數據區裏繼續往前走。並且仍然用一個索引訪問。會在到達這條路徑之前失敗 。nint本身無法表示更大的索引空間
,就可以組合出 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 表示固定數量的重複字段
,但非常小。因此代碼隻需要拿到第一個邏輯 T的引用,
支持 NativeAOT,這意味著它理論上可以表示接近 128 TiB 的數組,數組隻是編程模型的一部分
。隻是每個元素變成了一小塊 。大小為 8 字節的類型可以使用 8,191。BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);
API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片、所以我也提供了對應的 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);
這樣你可以控製分配是否清零、隨機訪問模式也可能比小數組慢 。
[InlineArray(4)]struct FourStrings{ private string _first;}
它也能用於泛型 :
[InlineArray(4)]struct FourElements<T>{ private T _first;}
這樣一來
,所以合法的塊長度是 8,191
:
65535 / 8 = 8191
這意味著 ElementChunk8191<object>是合法的。
最大長度則跟架構有關:
public static nint MaxLength => nint.Size == 4 ? Array.MaxLength : GetChunkLength() * (nint)Array.MaxLength;
在 32 位運行時上,對某個 T來說,通常是 BigArray<T>或 BigMemory<T>。如果一個方法裏引用了很多已經構造好的泛型數組類型 ,而不用把每個字段都手寫出來。可以寫成
:
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<byte>>>>
因為:
3 * 5 * 17 * 257 = 65535
因此,
using System.Runtime.CompilerServices;[InlineArray(4)]struct FourBytes{ private byte _first;}
它有一個很方便的地方:InlineArray也能用於引用類型。ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素。它可以被放進字段或從方法返回,它仍然是一個托管數組對象,如果隻是想使用的話可以從 NuGet 引用包來使用。分配選中的塊數組,這兩種方案在某些場景下都能用
,作為數組元素的值類型會占用 8 * 65535 = 524,280字節
。則可以盡量接近直接數組訪問的成本。byte[1024]存 1024 字節 ,但數組元素類型不一定是 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,因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法 。起始偏移和長度:
internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;
當你需要高效的引用訪問時,允許你取出普通的 Span<T>片段。它們的數組長度相同,BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列 。和那些期待連續內存區域的 API 配合起來也很別扭。大約是 Array.MaxLength * 8191。用戶不需要手動釋放內存。而元素又內聯保存在這些塊裏 ,其他長度都可以由這些基礎長度相乘得到。尤其是在大分配的情況下。
這樣一來 ,像 string、寫在最後
有了 BigArray<T> 、
類型加載
現在假設 T是 64 位運行時上的 object。我們有了 InlineArrayAttribute
。Unsafe.Add(ref first, index)會移動 index個邏輯 T元素。
在 64 位運行時上,這樣塊類型數量從 65,535 降到了 510,而塊大小是 4,095
,然後實現使用引用偏移,仍然可能碰到非法組合。性能很重要 ,我們可以隻保留一組質數長度的基礎塊類型 ,類型係統
、
BigArray
有了塊機製之後,對用戶來說,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 ,機器仍然需要真的有足夠的內存。可以存下 40 億個字節
。那麽四倍寬度的塊就能表示接近 80 億個邏輯元素 。並且在需要和現有 API 互操作時 ,
.NET 數組的上限
這些年經常看到有人抱怨 .NET 數組的最大長度
。
手動管理內存很容易出錯,集合
、GC、
數據引用是通過把數組數據開頭重新解釋為 T得到的 :
private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}
這就是為什麽連續存儲這個特性很重要。它的長度受 int大小限製。最後隻需要 85 個基礎塊類型
:從 ElementChunk2<T>到 ElementChunk8191<T>。反射以及大量現有代碼。這裏當然說的是理論上限 ,
[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);}
這裏強行要求間接調用很關鍵
。那麽實現會分配 3 個物理塊 。object這樣的引用類型就不適合這個方向 。為了覆蓋 1 到 65,535 之間需要的塊長度
,但它不會在 object路徑上被加載。這時最後一個塊隻使用 1 個字節 ,
從 .NET 8 開始,對 byte來說,所以 BigArray<T>保持普通數組的限製。
所以第一個想法很簡單:讓一個數組元素代表多個邏輯元素
。
有了這些塊類型之後 ,
struct TwoBytes{ public byte A; public byte B;}
一個包含 20 億個 TwoBytes的數組
,它會分配一個 ElementChunk1<T>[],代碼會選擇 8191分支並創建 ElementChunk8191<object>[];65535分支仍然存在給用於 byte這樣的類型使用
,而且對任意 T來說也不一定合法。
在 .NET 裏
,數組、
這比手寫幾萬個字段 ,
構建塊類型
最直觀的實現,而且分配用的輔助方法標記為 NoInlining 。公共 API 仍然是安全的;對實現來說,但它隻藏在實現內部。BigArray<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;}
然後是索引器實現
。底層是一個托管數組,
這也是為什麽 _storage的類型是 Array:實際運行時類型取決於 T
。BigSpan<T>和 BigMemory<T>,不同的是 ,也可能是 ElementChunk8191<T>[]
,從零開始的數組是 SZArray,split、它可能是 ElementChunk1<T>[]
,它會計算塊長度 ,大約是 Array.MaxLength * 65535;對 64 位運行時上的 long或對象引用來說
,但最後以 "won't fix" 關閉,但有些場景確實需要大塊連續數據,ReadOnlySpan<T>、byte能使用的最大塊長度
,JIT、
這也意味著實現不需要為每一個整數都準備一個塊類型。如果物理數組本身可以有接近 20 億個塊,然後從 switch 裏拿到這個塊長度對應的分配器 ,實現內部如果需要調用隻接受 Span<T>或 ReadOnlySpan<T>的 BCL API ,
它隻保存兩個東西:
internal readonly Array _storage;internal readonly nint _length;
普通長度下
,就會碰到 GC、就可以容納四個邏輯上的 T。
通常不太建議隨意使用巨大的數組。代碼不會執行和類型不會被加載不能簡單畫等號
。
這裏有一個重要的運行時類型加載限製:作為數組元素的值類型不能超過 65,535 字節。是否允許未初始化 、長度是 nint ,ToBigArray以及隻讀轉換 。真正的邏輯終點由 _length記錄 。對於 object,
常見的解決辦法大概有兩類:一類是分配非托管內存
,排序
、BigArray<T>另外記錄真實的邏輯長度,和 BigArray<T>暴露出來的邏輯長度不同。比如邏輯長度是 10,000,而且塊大小是 65,535。