PHP Generators

Generators internally simply implement Iterator interface and is a function that always returns generator object. Its syntax is similar to normal php functions except that in place of return it uses yield keyword. Thus iterates over dataset without being need to first load array in memory and then do further iteration over it.
While we have to work on large datasets like reading 10,000 records. Then we might face issues like out of memory or if we are iterating through array of 10,000 elements then its processing time significantly increases and script execution time get over .
Now what possible options we generally try are :
1. Increase the execution time in php.ini.
2. Increase the memory limit.

It would not be suitable to increase the memory limit because we don’t wish to dedicate our whole server memory to solve this specific task.

In these scenarios PHP Generators can improve the performance. Let’s have a look on some sample code given below:

function loadItemInArray ($items) {
    $arr = [];

    for ($i = 1; $i < $items; $i++) {
        $arr[] = $i;
    }

    return $arr;
}

foreach (loadItemInArray(15) as $item) {
    echo "$item<br>";
}
// This code is technically correct but will not work efficiently 
//large dataset
// This is an example of generator function and work efficiently
function getData ($items) {
    for ($i = 1; $i < $items; $i++) {
        yield $i;
    }
}
foreach (getData(PHP_INT_MAX) as $item) {
    echo "$item<br>";
}
//Here PHP_INT_MAX is the largest value of integer that your PHP //version supports

Now a question might arising in your mind what and how yield keyword is doing here….

Let’s take a one more example of generator function

<?php
function checkGeneratorFunction()
{
    yield;
}

$result = checkGeneratorFunction();
echo get_class($result);

// It will display 'Generator' as output.

As get_class() returns the name of the class of an object. So this implies that PHP takes any function with yield keyword as Generator function and treat it return or yield value as Generator object.

Leave a Reply

Your email address will not be published. Required fields are marked *