Repository navigation
Description
While System.Array API supports LongLength and operator this[long i], the CLR does not allow arrays to be allocated with more than 2^31-1 elements (int.MaxValue).
This limitation has become a daily annoyance when working with HPC or big data. We frequently hit this limit.
Why this matters
- .NET arrays is the de facto storage unit of many APIs & collections.
- Currently one has to allocate native memory instead, which does not work with managed code (Span could have helped, but it's been limited to int32 as well).
- HPC frameworks expects data to be contiguous in memory (i.e. the data cannot be split into separate arrays). E.g. BLAS libraries.
- Requires applications to be coded and designed differently if they handle <2G elements or >2G elements. I.e. It does not scale.
- It's an arbitrary limitation with little value to the user and application:
- With a desktop with 64GB, why can one only allocate 3.1% of its memory in one go?
- With a data centre machine with 1,536GB, why can one only allocate 0.1% of its memory in one go?
In C++ this is solved with std::size_t (whose typedef changes depending on the target platform). Ideally, .NET would have taken the same route when designing System.Array. Why they haven't is a mystery, given that AMD64 and .NET Framework appeared around the same time.
Proposal
I suggest that when the CLR/JIT runs the .NET application in x64, it allows the array long constructor to allocate more than int.MaxValue items:
- Indexing the array with operator this[long i] should work as expected and give access to the entire array.
- Indexing the array with operator this[int i] should work as expected but implicitly limit the access to only the first int.MaxValue elements.
- The LongLength property should return the total number of elements in the array.
- The Length property should return the total number of elements in the array, or throw OverflowException of there are more than int.MaxValue elements (this matches the current behaviour on multi-dimensional arrays with more than int.MaxValue elements).
I naively believe that the above should not break any existing application.
Bonus points for extending 64-bit support to Span and ReadOnlySpan.
Activity
tannergooding commentedon Mar 8, 2019
One of the simplest breaks becomes any program that is doing the following:
This works fine for any existing programs, since CoreCLR actually defines a limit that is just under
int.MaxValue. Allowing values that are greater thanint.MaxValuewould cause an overflow to-2147483648and either cause unexpected behavior or cause anIndexOutOfRangeExceptionto be thrown.giuliojiang commentedon Mar 8, 2019
I frequently run into this array when processing large chunks of data from network streams into byte arrays, and always need to implement chunking logic in order to be able to process the data.
It would be great to be able to use
longindexes on arraysGPSnoopy commentedon Mar 8, 2019
@tannergooding That's why I proposed above to keep the existing behaviour of throwing OverflowException on Length when there are more than int.MaxValue elements. Nothing changes there.
I'm suggesting that changing the CLR implementation as proposed above would allow applications and people who want to to use large arrays without breaking existing applications. You are right that simply passing a large array into a library that does not support it will break, but at least this will give us choice. We need to start somewhere, and .NET cannot keep ignoring this problem.
philjdf commentedon Mar 8, 2019
Yesterday I happily created an array in Python which contained more than two billion elements. When can I do the same in .NET?
Currently we get an exception if we try to construct an array with more than 2B elements. What's wrong with deferring that exception until something calls the
Lengthproperty which can no longer return a valid int? @tannergooding's example wouldn't cause problems. Are there other examples which break?GrabYourPitchforks commentedon Mar 21, 2019
This is an interesting idea, but I wonder if it would be better to have a
LargeArray<T>or similar class that has these semantics rather than try to shoehorn it into the existingArrayclass. The reason I suggest this course of action is that the GC currently has a hard dependency on the element count of any variable-length managed object fitting into a 32-bit signed integer. Changing the normalArrayclass to have a 64-bit length property would at minimum also affect theStringtype, and it may have other unintended consequences throughout the GC that would hinder its efficiency, even when collecting normal fixed-size objects. Additionally, accessing the existingArray.Lengthproperty would no longer be a simple one-instruction dereference; it'd now be an overflow check with associated branching.If we had a theoretical
LargeArray<T>class, it could be created from the beginning with a "correct" API surface, including even usingnuintinstead oflongfor the indexer. If it allowed T to be a reference type, we could also eliminate the weird pseudo-covariance / contravariance behavior that existingArrayinstances have, which would make writing to aLargeArray<T>potentially cheaper than writing to a normalArray.[-]Add 64-bit support to Array underlying storage[/-][+]Add 64 bits support to Array underlying storage[/+]GPSnoopy commentedon Apr 4, 2019
@GrabYourPitchforks interesting facts about the GC. I wasn't aware of such limitations.
A
LargeArray<T>class could be a temporary solution. My main concern is that it would stay a very niche class with no interoperability with the rest of the .NET ecosystem, and ultimately would be an evolutionary dead end. I do like the idea ofnuint/nintthough.My gut feeling is that
Array,Stringand the GC are ripe for a 64 bits overhaul. We should bite the bullet and do it. So far I've been quite impressed by the .NET Core team willingness to revisit old decisions and areas that Microsoft had kept shut in the past (e.g. SIMD/platform specific instructions,float.ToString()roundtrip fixes, bug fixes that change backward compatibility, etc).juliusfriedman commentedon Apr 5, 2019
I guess I could palette a LargeArray but if that's going to be implemented than I hope it doesn't create a new type which is not actually an Array, IMHO it would have been much easier to address this if we would have created another sub type of Array internally instead of inventing Span however Span also solves other problems....
GSPP commentedon Apr 22, 2019
These days 2GB arrays are barely enough for many applications to run reliably. RAM prices have stagnated for a few years now. Surely, the industry will resolve this problem sooner or later. As RAM amounts resume increasing at Moores law rate this 2GB array issue will become very commonplace sooner or later.
A
LargeArray<T>type might be a good medium term solution. But will 2GB arrays not be very commonplace 10 years from now? Do we then want to litter application code and API surfaces withLargeArray<T>? It would often be a hard choice whether to go forLargeArray<T>orT[].Thinking in the very long term it seems far better to find a way to fix
T[].GSPP commentedon Apr 22, 2019
If 64 bit support is implemented there could be a tool that analyzes your code for legacy patterns (e.g. usage of
int Lengthor the typical for loopfor (int i = 0; i < array.Length; i++)). The tool should then be able to mass upgrade the source code. This could be a Roslyn analyzer.GrabYourPitchforks commentedon Apr 24, 2019
Since this would be such a massive ecosystem breaking change, one other thing you'd probably have to do is analyze the entire graph of all dependencies your application consumes. If the change were made to
T[]directly (rather thanLargeArray<T>or similar), assemblies would need to mark themselves with something indicating "I support this concept!", and the loader would probably want to block / warn when such assemblies are loaded. Otherwise you could end up in a scenario where two different assemblies loaded into the same application have different views of what an array is, which would result a never-ending bug farm.juliusfriedman commentedon Apr 26, 2019
Not if large array was an array... i.e. derived from it if only internally perhaps; like I suggested back in the span threads.
GrabYourPitchforks commentedon Apr 27, 2019
If large array is a glorified array, then you could pass a large array into an existing API that accepts a normal array, and you'd end up right back with the problems as originally described in this thread.
GrabYourPitchforks commentedon Apr 27, 2019
Furthermore, I'm not sure I buy the argument that adding large array would bifurcate the ecosystem. The scenario for large array is that you're operating with enormous data sets (potentially over 2bn elements). By definition you wouldn't be passing this data to legacy APIs anyway since those APIs wouldn't know what to do with that amount of data. Since this scenario is so specialized it almost assumes that you've already accepted that you're limited to calling APIs which have been enlightened.
juliusfriedman commentedon Apr 27, 2019
You have LongLength on the Array
The only fundamental diff is that one is on the LOH and one is not.
By virtue of the same fact span wouldn't be able to hold more than such either so large span must be needed also...
146 remaining items
tannergooding commentedon Mar 20, 2024
CLS compliance notably doesn't really matter that much anymore and we've even looked at removing it in the past.
It was a consideration 20+ years ago when .NET was first introduced and there are technically some languages that may not support unsigned types. However, CLS Compliance itself hasn't been updated since then and doesn't take into account any new features (like
DIMs,ref structs, etc; many of which would likely not be considered CLS Compliant given the original spirit of the feature) and Roslyn doesn't itself accurately warn in all the places it "should" (which includes places wheremodreqmight be emitted, as is the case when using several language features withvirtualmembers).We've also, since .NET Core 2.1 at least, been a lot more flexible and overall consistent with exposing support for unsigned types where that makes sense or to ensure they have general parity with signed types (such as for Generic Math, conversion support, optimizations, Math and reading/writing APIs, etc).
So, if we truly thought that
unsignedwas appropriate, we'd end up having that discussion and using it. The biggest "blocker" is just that the rest of the ecosystem already uses signed types almost exclusively for the general indexing concept and so it simplifies many things to continue being consistent. We also get some of the other benefits like a clear sentinel for uninitialized or invalid state (think a sentinel similar tonull) and code being less error prone when doing things like computing offsets (smallOffset - largerOffsetis negative, not an overflow resulting in a very large positive), or doing reverse loop iterations, etc.I would expect the most likely thing to be some
NativeSpan<T>like type, which can track a large length and work for any type of data (including unsafely reinterpreting something like a largelong[]as aNativeSpan<byte>, since it might not be representable asSpan<T>).It might be conceivable to then define some
UnmanagedArray<T>(where T : unmanaged) which allows for safe allocation and cleanup of very large buffers, but I wouldn't expect it to ever work for reference types or structs that contain reference types (directly or indirectly) due to the overhead that places on the GC in tracking that many objects. It's also something that is easily pollyfilled by the community for the special scenarios that need it: https://source.terrafx.dev/#TerraFX/UnmanagedArray%25601.cs,6e619c21500b58b1MineCake147E commentedon Mar 20, 2024
You still have to check it in
Slice(start, length).runtime/src/libraries/System.Private.CoreLib/src/System/Span.cs
Line 413 in d58c541
runtime/src/libraries/System.Private.CoreLib/src/System/Span.cs
Line 410 in d58c541
Unsigned cast hack is not an exception of negativity check.
Yes. I knew it.
However, use of signed types for length still spreads misinformation that it could be negative.
There'd be plenty of user codes that check the sign bit of the length and/or index.
Additional question: Why do you need to reinterpret the values in signed types as unsigned one, if the signed types are better?
jkotas commentedon Mar 21, 2024
A lot has been written about advantages and disadvantages of signed and unsigned types for lengths. The general consensus is that signed lengths are less error prone for general higher-level programming that is focus of C# and .NET. Other much newer languages that target similar audience have made the same choice:
On the other hand, Rust that is more focused on low level programming has unsigned lengths.
Neme12 commentedon Mar 21, 2024
I don't think this is the appropriate discussion for that here. But my 2 cents are: While I like the appeal of unsigned lengths as something that can be correct by construction if your API never accepts negative values, so that you don't have to check for it on every input... in practice, unsigned lengths have many disadvantages - the biggest one being that if you have two unsigned values, you just can't take their difference, because the difference might not fit into an unsigned value. This is not only an annoying issue, but also a correctness issue, because even if you don't accept negative values, you often need them as part of your computation.
Even C++ introduced
ssize_tbecause of how cumbersomesize_tis.I would love it if there were unsigned types that had the same max value as corresponding signed types, just couldn't be negative - so you could always take their difference. Those would have none of the disadvantages of unsigned types. But unfortunately, this isn't how either the hardware or platforms are designed, and we have what we have. The best we can do given what we have are signed types.
Neme12 commentedon Mar 21, 2024
That's true but @MineCake147E still has a point (although I don't agree that unsigned would have more benefits than downsides). There are many places where you need to check than an
intis not negative for validation, often having nothing to do with array indexing, and even if it has to do with array indexing, on unsigned, you'll likely have a different code path (e.g. throw anArgumentExceptioninstead ofIndexOutOfRangeExceptinon).Although as I said, this isn't actually a benefit - in practice it's a problem.
huoyaoyuan commentedon Mar 21, 2024
I imagined letting the JIT insert some magic to adapt nint-length to 32bit indexing code. This will certainly bring some performance impact. Existing code shouldn't fail while processing small arrays. But yes, making them to have a chance of failing is painful.
MineCake147E commentedon Mar 21, 2024
Even Zen4 and Golden Cove need 1 clock cycle to perform
movsx rax, eax, while they need no clock cycle to zero-extend the value (Golden Cove needs the destination register to be different though).Golden Cove also has less instruction execution ports available for
movsxthan formovzxandmov edx, eax.MOVSX in uops.info
MOVZX in uops.info
mov r32, r32 in uops.info
This is why the carry flag exists.
JIT could optimize
subtract then comparepattern by just eliminating unnecessarycmpinstruction.Example C# code:
The JIT could optimize it to something like (in the future):
As I mentioned earlier, you can simply replace
i >= 0withi < Length, because -1 is nowMaxValue.Also, you can do the
dec rcx→jaeas well.I wonder what you mean here.
For
index,~0would just be fine, because~0wouldn't be a valid index for any length.For
Length, it depends on your intention.Neme12 commentedon Mar 21, 2024
Yeah... those should never have existed. If you have no value, just use
null(or better,Optional<T>).Xyncgas commentedon Mar 21, 2024
It's not like it's ok to index into array with negative int
the argument of underflow holds true another way : unsigned has a bigger max value (as signed allows going to negative)
0 - 2147483647 doesn't underflow using signed, 2147483647 + 2147483647 doesn't overflow using unsigned
the reasoning behind using unsigned for length I can see is now you can get an array with more than INT32.MaxValue elements
Practicality aside, it's computer it computes number and numbers are infinite
The benefit of using unsigned integer to represent counts and position in array is to avoid bugs, assuming the reasoning for unsigned number to represent these things are acceptable it would eventually appear here, and it's the valid reasoning brings the expectation that one day you are going to get unsigned int from a library but now you need to convert it to int and that might be causing problem in the future because it's intended to be an unsigned int
Neme12 commentedon Mar 22, 2024
I would say it's the opposite, unsigned numbers lead to more bugs (especially when combining them with or converting to/from signed numbers, which you often have to). Using a single data type for all kinds of integers has a huge advantage.
This discussion is pointless though, I'm pretty sure the API review board would never approve an unsigned data type for regular usage like length or indexing. At least not without a really good reason for why it's not only useful, but necessary.
gulp-sourcemapsceaseless commentedon Oct 16, 2025
tannergooding commentedon Oct 17, 2025
Closing this as not planned.
As per the above this is essentially "too breaking" to implement in practice. While there could be alternatives such as some
LongArraytype, this is both expensive to actually implement and pushes users towards a pit of failure where their app won't be portable and will likely have significantly worse performance than expected. -- The summary from above is that computers are not really designed to work with large memory (not like that at least) and having a lot of memory is not the same as it being a good idea to use it all in a singular allocation. The memory exists so that you can do more work in parallel (whether multiple apps or singular) without paging to disk. Working with large data generally necessitates chunking and parallelizing things to get the expected performance without bottlenecking and essentially "wasting" the resources that are available.If anything was done here, it would likely involve exposing additional helpers or APIs that allow more easily working with chunked data (such as further improving
SequenceReader) and would require its own proposals and example API usage.