Support for generators (via the yield keyword) has been added to PHP 5.5 and allows you to create simple iterators without the use of the Iterator interface. What’s this all mean? It boils down to overhead, generators use less memory than an implementation of the Iterator interface or simply creating an array that would contain the values.
Before looking at a generator, let’s take a look at a bit of code to generate an array with even numbers between 0 and 1 million:
Easy enough, right? Sure, but the peak memory usage (on my Mid 2012 Macbook Air) was about 70MB. Now let’s implement the same functionality using a generator function:
Was the bit more coding worth it? You better believe it! On the same system, the generator code used less than a quarter of a megabyte! Worth noting is that even though the generator used significantly less memory, it did perform slower at around 2.5 seconds compared to the 1.9 seconds without the generator. Like most things, YMMV and it’s always worth weighing the pros and cons when making your coding decisions.