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