The documentation states:

The generator allows you to write code that uses foreach to iterate over a dataset without having to create an array in memory, which can lead to you exceeding the memory limit, or it will take quite a long time to create it. Instead, you can write a generator function, which, in fact, is a normal function, except that instead of returning a single value, the generator can yield as many times as necessary to generate values ​​that allow the original data set to be iterated.

A good example of the above can be the use of the range () function as a generator. The standard range () function must generate an array consisting of values ​​and return it, which may result in the generation of huge arrays: for example, calling range (0, 1000000) will result in more than 100 MB of memory being used.

Alternatively, we can create an xrange () generator that uses memory only to create an Iterator object and save the current state, which requires no more than 1 kilobyte of memory.


If you want to make it, it’s time to generate. It can be used instead of the normal function.

The range () function as a generator. For example, it will be possible to use the standard range (), for example, the calling range (0, 1000000).

It can be used internally, it can be less than 1 kilobyte.


And an example is given:

function xrange($start, $limit, $step = 1) { if ($start < $limit) { if ($step <= 0) { throw new LogicException('Step must be +ve'); } for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } else { if ($step >= 0) { throw new LogicException('Step must be -ve'); } for ($i = $start; $i >= $limit; $i += $step) { yield $i; } } } /* * Note that both range() and xrange() result in the same * output below. */ echo 'Single digit odd numbers from range(): '; foreach (range(1, 9, 2) as $number) { echo "$number "; } echo "\n"; echo 'Single digit odd numbers from xrange(): '; foreach (xrange(1, 9, 2) as $number) { echo "$number "; } 

I increased the number of generations to 100000 :

The result is not much different. I figured that when using xrange() memory should be consumed less. Why is that?

    1 answer 1

    Because you forgot to use the result.

    It is necessary so:

     $a=range(0, 100000); 

    4474.390625

    https://repl.it/Fy4I/1

    A complete set of values ​​has been created.

     $a=xrange(0, 100000); 

    377.7890625

    https://repl.it/Fy4K/1

    Only one value extracted.