Loading…
Loading…
30 карточек
What patterns allow writing fully allocation-free code in C#?
нажми, чтобы перевернуть
Span<T>, stackalloc, ArrayPool<T>, and ref struct enables processing data without creating heap objects.ref and in parameters for structs to avoid copying.Span<T>: Instead of string.Substring() or List<T>, return slices of the original data.GetEnumerator() as a ref struct to avoid boxing in foreach.csharp public static bool TryParseInt(ReadOnlySpan<char> input, out int result) { // Parsing directly into Span, without creating intermediate strings }
Use BenchmarkDotNet with MemoryDiagnoser. The goal is Allocated = 0 per operation. Note that the JIT may inline small methods, but Span can sometimes prevent inlining due to ref struct constraints.
Trade-off: Allocation-free code is harder to read and maintain. Use it only after profiling, when allocations are proven to be a bottleneck.
Когда да
Когда нет
Совет на собеседовании
Ask about MemoryDiagnoser, ref struct constraints, and the impact on JIT inlining.
Свайп вправо — знаю, влево — не знаю
