Skip to content

Add 64 bits support to Array underlying storage #12221

Closed as not planned
Closed as not planned

Description

@GPSnoopy

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

  1. tannergooding commented on Mar 8, 2019

    @tannergooding
    Member

    I naively believe that the above should not break any existing application.

    One of the simplest breaks becomes any program that is doing the following:

    for (int i = 0; i < array.Length; i++)
    {
    }

    This works fine for any existing programs, since CoreCLR actually defines a limit that is just under int.MaxValue. Allowing values that are greater than int.MaxValue would cause an overflow to -2147483648 and either cause unexpected behavior or cause an IndexOutOfRangeException to be thrown.

  2. giuliojiang commented on Mar 8, 2019

    @giuliojiang

    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 long indexes on arrays

  3. GPSnoopy commented on Mar 8, 2019

    @GPSnoopy
    Author

    @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.

  4. philjdf commented on Mar 8, 2019

    @philjdf

    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 Length property which can no longer return a valid int? @tannergooding's example wouldn't cause problems. Are there other examples which break?

  5. GrabYourPitchforks commented on Mar 21, 2019

    @GrabYourPitchforks
    Member

    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 existing Array class. 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 normal Array class to have a 64-bit length property would at minimum also affect the String type, 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 existing Array.Length property 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 using nuint instead of long for the indexer. If it allowed T to be a reference type, we could also eliminate the weird pseudo-covariance / contravariance behavior that existing Array instances have, which would make writing to a LargeArray<T> potentially cheaper than writing to a normal Array.

  6. changed the title [-]Add 64-bit support to Array underlying storage[/-] [+]Add 64 bits support to Array underlying storage[/+] on Apr 4, 2019
  7. GPSnoopy commented on Apr 4, 2019

    @GPSnoopy
    Author

    @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 of nuint/nint though.

    My gut feeling is that Array, String and 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).

  8. juliusfriedman commented on Apr 5, 2019

    @juliusfriedman
    Contributor

    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....

  9. GSPP commented on Apr 22, 2019

    @GSPP

    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 with LargeArray<T>? It would often be a hard choice whether to go for LargeArray<T> or T[].

    Thinking in the very long term it seems far better to find a way to fix T[].

  10. GSPP commented on Apr 22, 2019

    @GSPP

    If 64 bit support is implemented there could be a tool that analyzes your code for legacy patterns (e.g. usage of int Length or the typical for loop for (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.

  11. GrabYourPitchforks commented on Apr 24, 2019

    @GrabYourPitchforks
    Member

    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 than LargeArray<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.

  12. juliusfriedman commented on Apr 26, 2019

    @juliusfriedman
    Contributor

    Not if large array was an array... i.e. derived from it if only internally perhaps; like I suggested back in the span threads.

  13. GrabYourPitchforks commented on Apr 27, 2019

    @GrabYourPitchforks
    Member

    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.

  14. GrabYourPitchforks commented on Apr 27, 2019

    @GrabYourPitchforks
    Member

    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.

  15. juliusfriedman commented on Apr 27, 2019

    @juliusfriedman
    Contributor

    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...

  16. 146 remaining items

  17. tannergooding commented on Mar 20, 2024

    @tannergooding
    Member

    they are not even CLS-compliant.

    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 where modreq might be emitted, as is the case when using several language features with virtual members).

    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 unsigned was 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 to null) and code being less error prone when doing things like computing offsets (smallOffset - largerOffset is negative, not an overflow resulting in a very large positive), or doing reverse loop iterations, etc.

    There are several possible ways to introduce huge arrays

    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 large long[] as a NativeSpan<byte>, since it might not be representable as Span<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,6e619c21500b58b1

  18. MineCake147E commented on Mar 20, 2024

    @MineCake147E
    Contributor

    The length for types like Array and Span are known to be "never negative" already, its an implicit assumption made by the runtime and which can only be violated by the user unsafely mutating the underlying state (which itself is undefined and dangerous behavior).

    You still have to check it in Slice(start, length).

    if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))

    if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)

    Unsigned cast hack is not an exception of negativity check.

    You only have a singular check for signed as well. Due to two's complement representation (x < 0) || (x >= KnownPositive) can just be emitted as (uint)x >= KnownPositive. It's an implicit optimization that is done by many compilers since all negatives will have the most significant bit set and will therefore compare as greater than KnownPositive

    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?

  19. jkotas commented on Mar 21, 2024

    @jkotas
    Member

    unsigned lengths

    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.

  20. Neme12 commented on Mar 21, 2024

    @Neme12

    Would you clarity about what's the drawbacks using unsigned types?

    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_t because of how cumbersome size_t is.

    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.

  21. Neme12 commented on Mar 21, 2024

    @Neme12

    No need for checking if the Length is negative

    The length for types like Array and Span are known to be "never negative" already, its an implicit assumption made by the runtime and which can only be violated by the user unsafely mutating the underlying state (which itself is undefined and dangerous behavior).

    No need for checking if the index is negative

    You only have a singular check for signed as well. Due to two's complement representation (x < 0) || (x >= KnownPositive) can just be emitted as (uint)x >= KnownPositive. It's an implicit optimization that is done by many compilers since all negatives will have the most significant bit set and will therefore compare as greater than KnownPositive

    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 int is 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 an ArgumentException instead of IndexOutOfRangeExceptinon).

    No need for reserving unused sign bit, hence twice the maximum representable size

    Although as I said, this isn't actually a benefit - in practice it's a problem.

  22. huoyaoyuan commented on Mar 21, 2024

    @huoyaoyuan
    Member

    .NET cannot make a breaking change here. As has been iterated many times, almost every single for loop written would now have a chance for silent failure. Any such change to make System.Array actually support 64-bits would have to be a hard break where roll forward was explicitly blocked and where there would need to be significant analyzer and language work to help surface the bugs users might hit (even though the vast majority of code would never actually encounter large arrays). There would likely be security and other concerns from such a break as well.

    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.

  23. MineCake147E commented on Mar 21, 2024

    @MineCake147E
    Contributor

    Many modern CPUs have zero-cost sign-extension as well.

    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 movsx than for movzx and mov edx, eax.
    MOVSX in uops.info
    MOVZX in uops.info
    mov r32, r32 in uops.info

    code being less error prone when doing things like computing offsets (smallOffset - largerOffset is negative, not an overflow resulting in a very large positive)

    This is why the carry flag exists.
    JIT could optimize subtract then compare pattern by just eliminating unnecessary cmp instruction.
    Example C# code:

    var s = length - start;
    return length > start ? s : 0;

    The JIT could optimize it to something like (in the future):

    xor eax, eax
    sub rdx, rcx    ; rdx = length - start
    cmova rax, rdx
    ret

    doing reverse loop iterations

    As I mentioned earlier, you can simply replace i >= 0 with i < Length, because -1 is now MaxValue.
    Also, you can do the dec rcx → jae as well.

    clear sentinel for uninitialized or invalid state (think a sentinel similar to null)

    I wonder what you mean here.
    For index, ~0 would just be fine, because ~0 wouldn't be a valid index for any length.
    For Length, it depends on your intention.

  24. Neme12 commented on Mar 21, 2024

    @Neme12

    clear sentinel for uninitialized or invalid state (think a sentinel similar to null)

    Yeah... those should never have existed. If you have no value, just use null (or better, Optional<T>).

  25. Xyncgas commented on Mar 21, 2024

    @Xyncgas

    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

  26. Neme12 commented on Mar 22, 2024

    @Neme12

    The benefit of using unsigned integer to represent counts and position in array is to avoid bugs

    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.

  27. removed
    needs-further-triage
    on Feb 9, 2025
  28. gulp-sourcemapsceaseless commented on Oct 16, 2025

    @gulp-sourcemapsceaseless
  29. tannergooding commented on Oct 17, 2025

    @tannergooding
    Member

    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 LongArray type, 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.

  30. locked and limited conversation to collaborators on Nov 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions