Performance optimization in PHP: A detailed description of the PHP generator

Source: Internet
Author: User
This article introduces to you about the performance of PHP in the optimization of the weapon: PHP generator of the detailed, there is a certain reference value, the need for friends can refer to, I hope you have some help.

If you are a small partner in Python or other languages, you should not be unfamiliar with generators. However, many PHP developers may not know the generator, perhaps because the generator is a PHP 5.5.0 only introduced functionality, or it can be the generator is not very obvious. However, generator functionality is really useful.


Just say the concept of confused you listen to the end of the story, so we first say that the merits, may be able to arouse your interest. So what are the advantages of the generator, as follows:

    • The generator will have a very big impact on the performance of your PHP application

    • PHP code saves a lot of memory when it runs

    • More suitable for calculating large amounts of data

So, how do these magical features work? Let's give an example first.

Concept Introduction

First, lay down the burden of the generator concept and look at a simple PHP function:

function Createrange ($number) {    $data = [];    for ($i =0; $i < $number; $i + +) {        $data [] = time ();    }    return $data;}

This is a very common PHP function that we often use when working with arrays. The code here is also very simple:

    1. We create a function.

    2. The function contains a for loop, which we loop to put the current time in $data

    3. forThe loop executes and $data returns.

It's not over, let's go. Let's write a function that loops out the return value of the function:

$result = Createrange (10); This invokes the function we created above, foreach ($result as $value) {    sleep (1);//pause here for 1 seconds, and we'll use    echo $value later. ' <br/> ';}

Let's look at the results of the operation in the browser:

It's perfect here, without any problems. (Of course the sleep(1) effect you can not see)

Think of a problem

We notice that the createRange value given when the function $number is called is 10, a very small number. Suppose, now pass a value 10000000 (10 million).

So, inside the function createRange , the for loop needs to be executed a few 1000 times. And there are 1000 thousands of values that are placed $data inside, and the $data array is placed inside the memory. Therefore, it consumes a lot of memory when calling the function.

Here, the generator is ready to go.

Creating generators

We directly modify the code, you pay attention to the observation:

function Createrange ($number) {for    ($i =0; $i < $number; $i + +) {        yield time ();}    }

Looking at this and just like the code, we deleted the array $data , and we didn't return anything, but we time() used a keyword beforeyield

Using the generator

Let's run the second piece of code again:

$result = Createrange (10); This invokes the function we created above, foreach ($result as $value) {    sleep (1);    echo $value. ' <br/> ';}

We miraculously discovered that the output value is not the same as the first time without using the generator. Here the value (timestamp) is spaced between 1 seconds.

The interval of one second is actually sleep(1) the result. But why is there no interval for the first time? That's because:

    • When the generator is not used: createRange The loop result inside the function for is quickly placed $data in and returned immediately. So, the foreach loop is a fixed array.

    • When using the generator: createRange The value is not a one-time fast build, but relies on foreach loops. foreachcycle once, for execute once.

Here, you should have a clue to the generator.

In-depth understanding of generators

Code anatomy

Let's dissect the code just now.

function Createrange ($number) {for    ($i =0; $i < $number; $i + +) {        yield time ();}    } $result = Createrange (10); This invokes the function we created above, foreach ($result as $value) {    sleep (1);    echo $value. ' <br/> ';}

Let's restore the code execution process.

    1. The function is called first, the createRange parameter is passed in 10 , but the for value is executed once and then stopped, and foreach the value that the first loop can use is told.

    2. foreachStart on the $result loop, come in first sleep(1) , and then start using for a given value to perform the output.

    3. foreachPrepares the second loop, before starting the second loop, it for requests the loop again.

    4. forThe loop then executes again, telling the generated timestamp foreach .

    5. foreachGet the second value, and output. Because foreach of sleep(1) this, the for loop is delayed by 1 seconds to generate the current time

So, throughout the execution of the code, there is always only one record value participating in the loop, and there is only one piece of information in memory.

The $number memory is always the value of a loop, no matter how large it starts, because all result sets are not immediately generated.

Conceptual understanding

Here, you should have probably understood what a generator is. Below we say the generator principle.

First, define a concept: the generator yield keyword is not a return value, his professional term is called the output value, just to generate a value

So foreach what is the loop in the code? In fact, PHP will return an object of a class when it uses the generator Generator . foreachyou can iterate over the object, and every iteration, PHP Generator calculates the next value that needs to be iterated through an instance. This foreach will tell you the next time you need to iterate over the value.

Also, it for stops immediately after the loop executes in the run. Wait for the foreach next cycle time again and for ask for the next value, the for loop will be executed again, and then immediately stop again. The end is not executed until the condition is not met.

Practical development of applications

Many PHP developers do not understand the generator, in fact, mainly do not understand the field of application. So, what are the applications of the generator in real-world development?

Read large files

PHP Development many times to read large files, such as CSV files, text files, or some log files. If these files are large, such as 5 G. At this point, it is not realistic to read all the contents into memory directly at once.

This generator can come in handy. A simple example: reading the text file

We create a text document and enter a few lines of text in it to sample the read.

<?phpheader ("content-type:text/html;charset=utf-8"); function Readtxt () {    # code ...    $handle = fopen ("./test.txt", ' RB ');    while (feof ($handle) ===false) {        # code ...        Yield fgets ($handle);    }    Fclose ($handle);} foreach (Readtxt () as $key = = $value) {    # code ...    echo $value. ' <br/> ';}

Through the output we can see that the code is completely normal.

However, the code execution rules behind it are a little bit different. Using the generator to read the file, first read the first line, the second read the second row, and so on, each time loaded into the memory of the text only one row, greatly reducing the use of memory.

This way, you can write code just like a small file, even if you don't have to worry about reading the text on G.

Related articles recommended:

Parsing of an array (generator) of dynamically generated content in PHP

New features of the generator in PHP7: Generator delegate (Yield-from) & return value (Return-value)

Simple parsing of PHP generator generators

Related Article

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: 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.