2 ms·
Generally speaking, transient buffers today, in performance sensitive code in NET, follow the pattern of T[]? toReturn = null; var buffer = length <= t
by neonsunset 2y ago
Generally speaking, transient buffers today, in performance sensitive code in NET, follow the pattern of
T[]? toReturn = null;
var buffer = length <= threshold
? stackalloc T[threshold]
: (toReturn = ArrayPool<T>.Shared.Rent(length));
/* logic */
if (toReturn != null) ArrayPool<T>.Shared.Return(toReturn);
either directly or via a buffer-like type that does it behind the scenes.
ArrayPool<T>.Shared is generally well-behaved in terms of GC, and small lengths will not even hit it, being practically free.
The amortized cost of this is substantially lower than allocating such arrays and then throwing them away: stackalloc, particularly for short lengths, is so cheap it might as well be noise, which is cheaper than still fast array alloc for short length, and as the length passes the threshold to avoid excessive stack pressure, it becomes faster to retrieve pre-allocated array from a threadlocal bucket within shared array pool.