In PHP, to work with a dataset, the natural thing to do is to use a loop, store the result to an array and return it. In today's tutorial, we introduce a solution by using a generator.
Return in a loop
For demonstration purposes, imagine we need a function that returns a series of numbers from one to twenty. Typically we will solve it this way:
However, storing a large set of data into an array is memory intensive.
We can do a simple benchmark by checking the memory used at run time:
The output is:
As we can see the memory used while looping the result set is about 1368 byte.
Yield in a loop
We can solve the problem using a generator, and the only difference is that we use yield instead of return:
And let's run the benchmark again, the output is shown s as below:
As we can see, we are using far less memory when using a generator.
There is one pitfall when using a generator though, we need to be aware, we are trading the speed with the memory utilization. It is like everything else in programming, there is no right solution but trade-offs.