C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Easy-to-write-but-inefficient recursive iterators

Chapter 6: Implementing iterators the easy way: n/a - never mentioned!

Created: 2/24/2008
Last updated: 2/24/2008

Suppose you have a tree structure you wish to iterate (either breadth or depth first). It's very easy to write an iterator which is O(n^2) - i.e. somewhat inefficient. By recursing and creating a new iterator each time, you end up creating a lot of iterators unnecessarily.

The solutions to this issue end up with less readable but more efficient code. It's up to you which path you take, of course, based on your context.

Wes Dyer and Eric have both blogged about this issue. See their posts for far more details.