Skip to content

Automatically stackalloc array allocations if they are assigned to a Span #12133

Open
@pakrym

Description

@pakrym

Considering that we know that allocated memory would not leave the stack JIT could optimize the following cases:

  1. When using a const as array size allocation can be turned into a stackalloc if it meets some predefined threshold for safe stackallocs.
Span<byte> bytes = new byte[20];
// ->
Span<byte> bytes = stackalloc byte[20];
Span<byte> bytes = new byte[2000];
// -> is not transformed because doesn't meet the threshold
Span<byte> bytes = new byte[2000];
  1. For dynamic array sizes condition might be transformed into an intrinsic:
Span<byte> bytes = new byte[lenght];
// ->
Span<byte> bytes = maybe_alloc_stack_bytes(lenght);
// where maybe_alloc_stack_bytes would be equivalent to lenght <= MAX_STACKALOC ? stackalloc byte[lenght]: new byte[lenght]

@jkotas @AndyAyersMS @davidfowl @KrzysztofCwalina

category:cq
theme:stack-allocation
skill-level:expert
cost:large

Metadata

Metadata

Assignees

No one assigned

    Labels

    JitUntriagedCLR JIT issues needing additional triagearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions