Looking at some of the code System.Linq I’ve come across some examples of Buffer<TSource> being used.
In the example of Enumemerable.ReverseIterator what is the benefit of using a Buffer?
private static IEnumerable<TSource> ReverseIterator<TSource>(
IEnumerable<TSource> source)
{
Buffer<TSource> buffer = new Buffer<TSource>(source);
for (int i = buffer.count - 1; i >= 0; --i)
yield return buffer.items[i];
}
Well something needs to read the entirety of the sequence, so that it can then return them in the reverse order.
Buffer<TSource>is one option here, and an efficient one – but it could be implemented withToArray()orToList(). A buffer allows an “oversized” array to be created (in the same way as it would for a list, but with less versioning etc) without the final “trim” step which would be present inToArray.You might find some of my Edulinq (my reimplementation of LINQ to Objects for fun and education) articles interesting, including:
ToArrayReverse(Deliberately in that order, as they show an evolution leading towards a similar “buffer” idea.)