Open
Description
Considering that we know that allocated memory would not leave the stack JIT could optimize the following cases:
- 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];
- 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