What is the difference between a generator and an array?

后端 未结 4 691
面向向阳花
面向向阳花 2021-01-31 15:35

Today the PHP team released the PHP 5.5.0 version, which includes support for generators. Reading the documentation, I noticed that it does exactly what it coul

4条回答
  •  日久生厌
    2021-01-31 16:03

    The difference is in terms of efficiency. For example, many languages other than PHP include two range functions, range() and xrange(). This is a really good example of generators and why to use them. Let's build our own:

    function range($start, $end) {
        $array = array();
        for ($i = $start; $i <= $end; $i++) {
            $array[] = $i;
        }
        return $array;
    }
    

    Now that's really straight forward. However, for large ranges, it takes a HUGE amount of memory. If we tried to run it with $start = 0 and $end = 100000000, we'd likely run out of memory!

    But if we used a generator:

    function xrange($start, $end) {
        for ($i = $start; $i <= $end; $i++) {
            yield $i;
        }
    }
    

    Now we use constant memory, yet still have an "array" (like structure) that we can iterate over (and use with other iterators) in the same space.

    It doesn't replace an array, but it does provide an efficient way of avoiding to need the memory...

    But it also provides savings in terms of the generation of items. Since each result is generated as-needed, you could delay execution (fetching or computing) each element until you needed it. So for example, if you needed to fetch an item from a database and do some complex processing around each row, you could delay that with a generator until you actually need that row:

    function fetchFromDb($result) {
        while ($row = $result->fetchArray()) {
            $record = doSomeComplexProcessing($row);
            yield $record;
        }
    }
    

    So if you only needed the first 3 results, you'd only process the first three records.

    For more info, I wrote a blog post on this exact subject.

提交回复
热议问题