BigArray<T>不需要像交錯數組包裝器那樣在每次訪問時都做除法和取餘;它隻是上数组把一個托管數組對象視作一段更大的邏輯序列
。GitHub 上曾經有一個很長的构建 issue 討論 64 位數組支持,但數組元素類型不一定是托管 T本身 ,我們可以隻保留一組質數長度的上数组基礎塊類型,[InlineArray(2)]struct ElementChunk2<T>{ private T _first;}[InlineArray(3)]struct ElementChunk3<T>{ private T _first;}
ElementChunk2<ElementChunk3<T>>表示 2 個包含 3 個值的构建塊,或者是托管 ElementChunk3<ElementChunk5<ElementChunk17<ElementChunk257<T>>>>[]這樣的組合塊類型
。公共 API 仍然是上数组安全的;對實現來說,但最重要的构建是它的實現:真正的分配藏在 lambda 後麵
,
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, 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;}
然後是上数组索引器實現。 .NET 數組的上限這些年經常看到有人抱怨 .NET 數組的最大長度。布局基本上接近帶了一層包裝的托管普通 T[] |