3 ms·
It's something you should rely on the language to optimize, but it always helps to not allocate frivolously if you can help it. I'm talking about using StringB
by chuckadams 2y ago
It's something you should rely on the language to optimize, but it always helps to not allocate frivolously if you can help it. I'm talking about using StringBuilder rather than concatenation, avoiding unnecessary boxed types, etc. Pooling every last thing doesn't do performance any favors mind you -- the tenured generation is expensive to collect, whereas eden is just a pointer bump.
- neonsunset 2y agoGenerally 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.