Skip to main content

Generators

Generators are a programming structure that allows to iterate over a large number of items without the need to store them all at once. For example, consider this code:

int[] array = // lots of numbers
foreach(int v in array)
Console.WriteLine(v);

This code first allocates the entire array, then prints its items one at a time. This allocation is a waste of not only memory, but also the computing spent on managing that memory, which could be avoided if each item was allocated right before printing it and then deallocated right away.

Many of the algorithms implemented in Nancy need to work on large numbers of elements, but one at a time. Via methods such as Curve.Cut() and Curve.CutAsEnumerable(), the library allows for controlling when the elements are allocated without changing the code using these elements, leveraging C# support for generators (yield, IEnumerable, LINQ, etc.).

For a longer introduction to this topic, you can check Raffaele Zippo's PhD Thesis, Appendix A.