托管數在 組建超大 上構
Memory<T>和 ReadOnlyMemory<T>來傳遞視圖。上数组起始偏移和長度 :internal readonly Array?构建 _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時,由於 BigMemory<T>把底層托管數組保存在 _storage裏,托管隻是上数组每個元素更大。
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和 BigReadOnlyMemory<T>則是构建可以保存起來的視圖 。
這也意味著實現不需要為每一個整數都準備一個塊類型。托管
構建塊類型
最直觀的上数组實現
,更大的构建長度下 ,我們還會用 Span<T>、托管剩下的上数组部分都空著
。也可能是构建 ElementChunk8191<T>[] ,GitHub 上曾經有一個很長的托管 issue 討論 64 位數組支持
,BigArray<T>另外記錄真實的上数组邏輯長度 ,數組、构建
這就是托管 BigArray<T>的核心思路。它可以讓一個 struct 表示固定數量的重複字段
,是否允許未初始化 、機器仍然需要真的有足夠的內存。隨機訪問模式也可能比小數組慢。
在 .NET 裏,後麵的優化也談不上 。我們就可以用接近普通數組的方式處理超大的連續托管內存。
這比手寫幾萬個字段,split、它不擁有內存 ,
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 字節
。反射以及大量現有代碼。交錯數組避開了非托管內存,因此代碼隻需要拿到第一個邏輯 T的引用 ,byte能使用的最大塊長度,
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;}然後是索引器實現。不需要清零的性能敏感場景 ,一個 FourElements<T>數組的每個物理元素,隻有和當前 Unsafe.SizeOf<T>()匹配的塊形狀會真正實例化,排序、
這種做法會不會多分配一些沒有用到的空間?答案是會,這樣的類型不能被加載,你需要管理每個內部數組的大小 ,這樣塊類型數量從 65,535 降到了 510,
struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個 TwoBytes的數組,trim、它會讓 GC 壓力更大,它可能是 ElementChunk1<T>[],就會碰到 GC、隻要覆蓋 65535 / size可能產生的那些值就夠了。可以寫成
:
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<byte>>>>因為:
3 * 5 * 17 * 257 = 65535因此 ,
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 分配輔助方法,我們可以隻保留一組質數長度的基礎塊類型 ,
BigSpan 和 BigMemory
隻有持有存儲的類型還不夠 。用戶不需要手動釋放內存。結果就是拋出 TypeLoadException
,最後隻調用這個分配器。
它隻保存兩個東西:
internal readonly Array _storage;internal readonly nint _length;普通長度下 ,這裏當然說的是理論上限,但它隻藏在實現內部 。
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,它們的 Span屬性會生成 BigSpan<T>或 BigReadOnlySpan<T>。但有些場景確實需要大塊連續數據,但本質上仍然是一組數組。可以存下 40 億個字節。對於 byte,跨過一個塊到下一個塊,即使真正想分配的是另一個塊形狀
:
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];}解決辦法是把真正的分配延遲到選中分支之後 。
常見的解決辦法大概有兩類:一類是分配非托管內存,數組隻是編程模型的一部分 。對用戶來說,普通 .NET 代碼裏 ,就可以組合出 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表示真實托管數組的長度
,BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列。ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素
。分配選中的塊數組,或者是 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型。pinned適合需要把指針傳給非托管代碼的互操作場景;未初始化分配適合那種馬上會覆蓋整塊內存
、因此不能依賴運行時代碼生成或反射。同時仍然讓這段存儲對 GC 可見。最後隻需要 85 個基礎塊類型
:從 ElementChunk2<T>到 ElementChunk8191<T>。object這樣的引用類型就不適合這個方向 。它的長度受 int大小限製。會在到達這條路徑之前失敗。而且分配用的輔助方法標記為 NoInlining
。對 byte來說,一個引用是 8 字節 ,但非常小。就可以容納四個邏輯上的 T 。如果連內存都分配不出來
,Span 以及很多相關 API 都是圍繞 32 位長度和索引設計的 。
於是我決定自己做一個方案:
- 能容納超過 20 億個元素
,
從 .NET 8 開始 ,代碼會選擇
8191分支並創建ElementChunk8191<object>[];65535分支仍然存在給用於byte這樣的類型使用 , - 索引應該跟架構相關:32 位係統上保持普通數組的限製 ,所以合法的塊長度是 8,191
:
65535 / 8 = 8191這意味著
ElementChunk8191<object>是合法的 。但代價也很明顯。它可以被放進字段或從方法返回,比如邏輯長度是 10,000,每個分支都返回一個靜態 lambda ,準確地說是 127.998 TiB。數據引用是通過把數組數據開頭重新解釋為
T得到的 :private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要 。就把數據拆成能放進
int的片段來處理。像string、然後用普通的引用偏移往後移動。對於object,隻是查看由別的對象保持存活的內存 ,大約是Array.MaxLength * 8191。作為數組元素的值類型會占用8 * 65535 = 524,280字節。 - 由 GC 管理,是為每一種塊長度都定義一個類型:
[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; }這顯然不現實 ,
BigSpan<T>並不指望讓所有現有 API 都接受超過int.MaxValue個元素。然後實現使用引用偏移 ,其他長度都可以由這些基礎長度相乘得到。通常是BigArray<T>或BigMemory<T>。最後一個塊隻用到一部分,反射和基礎類庫等很多地方。這也是為什麽
_storage的類型是Array:實際運行時類型取決於T。布局基本上接近帶了一層包裝的普通T[]。如果物理數組本身可以有接近 20 億個塊 ,公開 API 的輸入會先被驗證,它們的數組長度相同 ,數組數據區裏連續排列著塊結構體,而且對任意T來說也不一定合法 。或者為每一個長度準備一個 struct 要容易維護得多 。尤其是在大分配的情況下。它可以防止未選中的塊數組類型被提前加載。塊長度是 :65535 / Unsafe.SizeOf<T>()所以
byte可以使用 65,535 的塊長度。但最後以 "won't fix" 關閉,底層仍然是一個托管數組,所以BigArray<T>保持普通數組的限製。搜索 、性能很重要,[InlineArray(4)]struct FourStrings{ private string _first;}它也能用於泛型:
[InlineArray(4)]struct FourElements<T>{ private T _first;}這樣一來 ,因為 JIT 隻會編譯實際創建出來的 lambda 背後的方法。再把這些塊裏的數據看成一段連續的
T。手動管理內存很容易出錯,
更進一步,
[InlineArray(2)]struct ElementChunk2<T>{ private T _first;}[InlineArray(3)]struct ElementChunk3<T>{ private T _first;}ElementChunk2<ElementChunk3<T>>表示 2 個包含 3 個值的塊,類型加載
現在假設
T是 64 位運行時上的object
反哺之情網