Skip to content

Enumerable.Chunk throws OutOfMemoryException for very large chunk sizes. #67132

@madelson

Description

@madelson

Description

The exception is thrown even if the actual size of the enumerable is very small and the operation could (in theory) complete.

Reproduction Steps

new[] { 1 }.Chunk(int.MaxValue).ToArray();

Expected behavior

Returns a single element enumerable with a single chunk array of length 1.

Actual behavior

Throws OutOfMemoryException due to attempting to allocate a large array.

Regression?

No response

Known Workarounds

No response

Configuration

.NET 6, VS2022, Windows 10 x64.

Other information

One could argue that this shouldn't be fixed because callers just shouldn't ask for chunks that large. However, this can come up when using int.MaxValue as a means of "disabling" chunking/batching, especially when said batching is performed deeper in the call stack.

A fix for this would be to special case the creation of the first chunk when size is above a certain threshold. For large sizes, we can assume that the chunk probably won't fill and therefore we can build up to the full size (as is done for ToArray() rather than starting by trying to allocate the final array).

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.LinqenhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions