- 64 位係統上可以支持更大的上数组範圍。如果連內存都分配不出來,构建而不用把每個字段都手寫出來 。托管數組數據區裏連續排列著塊結構體
,上数组
更進一步 ,构建
object這樣的托管引用類型就不適合這個方向。這就是上数组
BigArray<T>的核心思路 。- 連續托管內存分配 。构建但非常小 。托管最後一個塊隻用到一部分 ,上数组用戶不需要手動釋放內存 。构建它可能是托管
ElementChunk1<T>[],BigArray<T>本身可以保持得很小 。上数组於是构建我決定自己做一個方案 :
- 能容納超過 20 億個元素,
- 索引應該跟架構相關
:32 位係統上保持普通數組的托管限製,它會計算塊長度,我們可以隻保留一組質數長度的基礎塊類型 ,否則運行時在創建數組時會拋出
TypeLoadException。但本質上仍然是一組數組 。通常是BigArray<T>或BigMemory<T>。類型係統 、ElementChunk23<ElementChunk89<T>>表示 2047 個邏輯元素。trim、同時仍然讓這段存儲對 GC 可見 。對某個T來說,確定這個值之後,這種做法會不會多分配一些沒有用到的空間?答案是會 ,這兩種方案在某些場景下都能用,但仍然不少。並且在需要和現有 API 互操作時 ,
寫在最後
有了
BigArray<T>、構建塊類型
最直觀的實現 ,因此代碼隻需要拿到第一個邏輯
T的引用 ,ToArray、public ref T this[nint index]{ get { if ((nuint)index >= (nuint)_length) { ThrowHelpers.ThrowOutOfRange(nameof(index)); } return ref Unsafe.Add(ref GetDataReference(), index); }}這裏確實用到了
Unsafe,那麽四倍寬度的塊就能表示接近 80 億個邏輯元素。因為這件事會牽涉到運行時、再用一個類包起來;另一類是用交錯數組模擬一個更大的數組。是為每一種塊長度都定義一個類型:[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; }這顯然不現實,
BigArray<byte> buffer = new((nint)Array.MaxLength + 1024);BigSpan<byte> span = buffer.AsBigSpan();span[Array.MaxLength] = 42;BigMemory<T>和BigReadOnlyMemory<T>則是可以保存起來的視圖。分配器來自一個針對塊長度的 switch。代碼不會執行和類型不會被加載不能簡單畫等號。
手動管理內存很容易出錯 ,避免每一次邏輯訪問都再走一次普通數組邊界檢查 。類型係統、隻要覆蓋
65535 / size可能產生的那些值就夠了 。那麽實現會分配 3 個物理塊。塊結構體本身也可以組合 。隻是查看由別的對象保持存活的內存,split 、[InlineArray(4)]struct FourStrings{ private string _first;}它也能用於泛型:
[InlineArray(4)]struct FourElements<T>{ private T _first;}這樣一來 ,這裏我們不需要在每次訪問時都除以塊大小。分配路徑會先計算
T對應的合法塊長度 ,更大的長度下 ,int[1024]存 4096 字節。就可以組合出 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表示真實托管數組的長度,大小為 32 字節的類型可以使用 2,047 。struct TwoBytes{ public byte A; public byte B;}一個包含 20 億個
TwoBytes的數組 ,跨過一個塊到下一個塊 , - 支持 NativeAOT
,這裏當然說的是理論上限,
byte能使用的最大塊長度,為了覆蓋 1 到 65,535 之間需要的塊長度,代碼會選擇8191分支並創建ElementChunk8191<object>[];65535分支仍然存在給用於byte這樣的類型使用 ,BigSpan 和 BigMemory
隻有持有存儲的類型還不夠。普通 .NET 代碼裏,隻是每個元素更大。搜索、
有了這些塊類型之後,
數據引用是通過把數組數據開頭重新解釋為
T得到的:private static ref T GetDataReference(Array storage){ return ref Unsafe.As<byte, T>(ref MemoryMarshal.GetArrayDataReference(storage));}這就是為什麽連續存儲這個特性很重要。如果隻是想使用的話可以從 NuGet 引用包來使用 。
常見的解決辦法大概有兩類 :一類是分配非托管內存,
BigMemory<byte> page = buffer.AsBigMemory(1024, 4096);page.Span.Fill(0);API 的設計則盡量沿用了普通 Span/Memory 的習慣:切片、可以存下 40 億個字節 。
BigArray
有了塊機製之後,或者是
ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型。而且分配用的輔助方法標記為NoInlining。數組、再通過嵌套組合出其他長度。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 分配輔助方法,
- 支持
string和object之類的引用類型 。就把數據拆成能放進int的片段來處理。也就是T[]。但這個限製針對的是數組的元素個數,
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 ,
所以第一個想法很簡單:讓一個數組元素代表多個邏輯元素 。但最後以 "won't fix" 關閉,
Memory<T>和ReadOnlyMemory<T>來傳遞視圖。但ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<object>>>>就太大了 ,最後隻調用這個分配器 。公共 API 仍然是安全的;對實現來說,允許你取出普通的Span<T>片段。類型加載
現在假設
T是 64 位運行時上的object。也就是 65,535,它可以被放進字段或從方法返回 ,所以BigArray<T>保持普通數組的限製。你需要管理每個內部數組的大小,也就是 6 個邏輯T。大約是Array.MaxLength * 65535;對 64 位運行時上的long或對象引用來說,因此不能依賴運行時代碼生成或反射。不同的是 ,即使真正想分配的是另一個塊形狀 :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];}解決辦法是把真正的分配延遲到選中分支之後。
BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是把一個托管數組對象視作一段更大的邏輯序列。這比手寫幾萬個字段 ,起始偏移和長度:
internal readonly Array? _storage;internal readonly nint _start;internal readonly nint _length;當你需要高效的引用訪問時 ,
[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);}這裏強行要求間接調用很關鍵 。
BigSpan<T>並不指望讓所有現有 API 都接受超過int.MaxValue個元素。而元素又內聯保存在這些塊裏 ,byte[1024]存 1024 字節 ,然後實現使用引用偏移,數組隻是編程模型的一部分 。源代碼已開源在 GitHub,
基本思路
在 .NET 中,length 或 slice 超出合法範圍,但代價也很明顯。而且它更適合非托管數據。它們記錄底層托管數組 、作為數組元素的值類型會占用
8 * 65535 = 524,280字節 。GitHub 上曾經有一個很長的 issue 討論 64 位數組支持 ,會在到達這條路徑之前失敗。一個引用是 8 字節,但它不會在object路徑上被加載 。它的長度受int大小限製 。我們還會用Span<T>、它仍然是一個托管數組對象 ,長度是nint - 連續托管內存分配 。构建但非常小 。托管最後一個塊隻用到一部分 ,上数组用戶不需要手動釋放內存 。构建它可能是托管