Background and Motivation
It is not uncommon, in performance oriented code, to want to stackalloc for small/short-lived collections. However, the exact size is not always well known in which case you want to fallback to creating an array instead.
Proposed API
namespace System.Runtime.CompilerServices
{
public static unsafe partial class Unsafe
{
public static Span<T> Stackalloc<T>(int length);
public static Span<T> StackallocOrCreateArray<T>(int length);
public static Span<T> StackallocOrCreateArray<T>(int length, int maxStackallocLength);
}
}
These APIs would be intrinsic to the JIT and would effectively be implemented as the following, except specially inlined into the function so the localloc scope is that of the calling method:
public static Span<T> StackallocOrCreateArray<T>(int length, int maxStackallocLength)
{
return ((sizeof(T) * length) < maxStackallocLength) ? stackalloc T[length] : new T[length];
}
The variant that doesn't take maxStackallocLength would use some implementation defined default. Windows currently uses 1024.
Any T would be allowed and the JIT would simply do new T[length] for any types that cannot be stack allocated (reference types).
Background and Motivation
It is not uncommon, in performance oriented code, to want to
stackallocfor small/short-lived collections. However, the exact size is not always well known in which case you want to fallback to creating an array instead.Proposed API
These APIs would be
intrinsicto the JIT and would effectively be implemented as the following, except specially inlined into the function so thelocallocscope is that of the calling method:The variant that doesn't take
maxStackallocLengthwould use some implementation defined default. Windows currently uses1024.Any
Twould be allowed and the JIT would simply donew T[length]for any types that cannot be stack allocated (reference types).