Modern PHP new features series (iv)-creation and use of generators

Source: Internet
Author: User
Tags spl virtual private server

1. Overview

The generator is a new feature introduced in PHP 5.5, but it is a very useful feature that few people use to visually.

Generators and iterators are a bit similar, but unlike standard PHP iterators, PHP generators do not require classes to implement the iterator interface, which reduces the overhead and burden of classes. The generator calculates and outputs the values that need to be iterated on a per-demand basis, which can have a significant impact on the performance of the application: if a standard PHP iterator often performs iterative operations in memory, it is computationally inefficient, and if you want to calculate large amounts of data in a specific way, such as manipulating Excel table data, Have more impact on performance. At this point we can use the generator to calculate and produce the subsequent values instantly, without taking up valuable memory space.

2. Creating generators

The builder is simple to create because the generator is a PHP function that uses the yield keyword one or more times in a function. Unlike normal PHP functions, the generator never returns a value, only produces a value. The following is a simple generator implementation:

function Getlaravelacademy () {    yield ' http://LaravelAcademy.org ';    Yield ' Laravel college ';    Yield ' Laravel Academy ';}

It's simple! When this generator function is called, PHP returns an object belonging to the generator class, which can iterate with the foreach function, and PHP will require the generator instance to compute and provide the next value to iterate over each iteration. The elegance of the generator comes after each output of a value, the internal state of the generator pauses; When the next value is requested from the generator, the internal state is restored. The state inside the generator switches between pauses and restores until it reaches the end of the function definition body or encounters an empty return statement. We can use the following code to invoke and iterate over the generators defined above:

foreach (Getlaravelacademy () as $yieldedValue) {    echo $yieldedValue, Php_eol;}

The above code output is as follows:

Http://LaravelAcademy.orgLaravel College Laravel Academy

3. Using generators

Here we implement a simple function to generate a range of values to illustrate how the generator saves memory. First we use iterators to achieve:

function Makerange ($length) {    $dataSet = [];    for ($i =0; $i < $length; $i + +) {        $dataSet [] = $i;    }    return $dataSet;} $customRange = Makerange (1000000), foreach ($customRange as $i) {    echo $i. Php_eol;}

Execution will cause an error, indicating that a single PHP process memory limit is exceeded (to provide memory space for 1 million digits):

Let's improve the implementation, using the generator to implement the following:

function Makerange ($length) {for    ($i =0; $i < $length; $i + +) {        yield $i;    }} foreach (Makerange (1000000) as $i) {    echo $i. Php_eol;}

The result can be printed without pressure again, because the generator only needs to allocate memory for an integer at a time.

In addition, a common use case is to iterate through the stream resources (file, audio, etc.) using the generator. Suppose we want to iterate over a CSV file of size 4GB, and the Virtual Private server (VPS) only allows PHP to use 1GB memory, so the entire file cannot be loaded into memory, and the following code shows how to do this using the generator:

function GetRows ($file) {    $handle = fopen ($file, ' RB ');    if ($handle = = FALSE) {        throw new Exception ();    }    while (feof ($handle) = = = FALSE) {        yield fgetcsv ($handle);    }    Fclose ($handle);} foreach ($getRows ($file) as $row) {    print_r ($row);}

The example above allocates memory for one row in the CSV file at a time, instead of reading the entire 4GB CSV file into memory.

4. Summary

Generators are a tradeoff between functional diversity and simplicity, and the generator is just a forward iterator, which means that you cannot use a generator to perform a back, fast forward, or find operation in a dataset, only that the generator calculates and outputs the next value. It is best to use the generator when iterating over large datasets or columns because it consumes the least amount of system memory. The generator can also perform simple tasks that the iterators can accomplish, and use less code.

All in all, the generator does not add new functionality to PHP, but using the builder greatly simplifies some tasks and uses less memory, and if you need more functionality, such as performing back, fast forward, and find functions in a dataset, it's best to write your own class that implements the iterator interface. Or use one of the native iterators (http://php.net/manual/spl.iterators.php) in the PHP standard library (SPL).

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.