Allocation-free Batching in Anchor 4

Traditionally, converting a large collection into batches requires a lot of array allocation and copying operations. Using an offset and count sounds like a good alternative, but very few APIs support it.

This is where the BatchAsSegments extension method comes into play. Rather than returning a new collection, it gives a window into the underlying list. The return type is IEnumerable<ReadOnlyListSegment<T>>.

ReadOnlyListSegment is a struct with 3 fields, a source list, an offset, and a count. It can be cast into a IList<T> or IReadonlyList<T>, but that’s not recommended because it requires a boxing operation and the goal of this is to allocation-free.

Enumerating the ReadOnlyListSegment can be done via an IEnumerable/IEnumerator pair as usual, but again that requires allocation. As an alternative, you can perform a for-each loop against it directly using a struct based enumerator. This is inspired by the enumerator on List<T>.

Leave a Reply

Your email address will not be published. Required fields are marked *