When Custom Iterators Beat Generators
You'll learn when to write custom iterators instead of using generators for more precise control.
Generators (which you'll learn soon) offer a convenient shorthand for creating iterators, but manual iterator implementation sometimes gives you capabilities that generators can't easily provide.
Core Concept
Custom iterators shine when you need fine-grained control over iteration state, complex cleanup logic, or advanced features like return() and throw() methods. While generators are great for simple sequential iteration, hand-crafted iterators give you complete authority over every aspect of the iteration lifecycle.
When Manual Iterators Win
Shared State Across Multiple Iterators: When you need several iterator instances sharing and modifying the same underlying data structure, custom iterators let you architect this precisely.
Complex Early Termination: If you need sophisticated cleanup that depends on how iteration stopped (break, exception, explicit call to return()), custom return() methods give you that control.
Performance-Critical Code: Manual iterators avoid the overhead of generator function state machines, which matters in tight loops or high-frequency operations.
Advanced Error Recovery: Custom throw() implementations can handle errors and decide whether to continue iteration, resume from a checkpoint, or abort completely.
Iterator Reuse Patterns: The iterable-iterator pattern (where an object can spawn fresh iterators) is more explicit and debuggable when written manually.
Think of it this way: Generators are like automatic transmission—easy and sufficient for most driving. Custom iterators are manual transmission—more work, but you get precise control when performance or special handling matters.
Key Takeaway: Choose custom iterators over generators when you need precise control over state, cleanup, error handling, or performance optimization that generators can't easily express.