Generator delegation in PHP 7

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
A common programming task is iterating over a collection of data. PHP being dynamically typed usually does not differentiate the data when iterating, consequentially large arrays in memory tend to take up more memory and may exceed memory limits or provide increased transaction times both having a negative impact on the user experience. PHP has functionality known as generator delegation, which takes data and passes it into a foreach loop without building an array. Rather the generator yields one value at a time to the calling foreach loop removing the need to copy the data into a large array.

Consider the following code example which runs smoothly...
PHP:
<?php
    function myGenerator() {
        for($i = 0; $i <= 1000000000; $i++) {
        yield rand(10,10000);
          }
    }

    foreach (myGenerator() as $myRandomNumber) {
      echo "$myRandomNumber\n";
    }
?>
Whereas the following code runs out of memory...
PHP:
<?php
    function myGenerator() {
      $numbers = array();
        for($i = 0; $i <= 1000000000; $i++) {
        array_push($numbers, rand(10,10000));
          }
      return $numbers;
    }

    foreach (myGenerator() as $myRandomNumber) {
      echo "$myRandomNumber\n";
    }
?>
It's worth noting that you can return a value from a generator and access it later on with generator return expressions.

By using a generator we can iterate over large sets of data without building a gigantic structure in memory improving application performance and reducing memory consumption. What do you think about PHP generator delegation? Will you use this technique in your programs or stick to old style foreach loops over arrays?
 
Last edited: