Performance optimizations that are ignored in php: generators

Source: Internet
Author: User

Tag: do not use the time () code to execute the target Val conditional BSP ext effect

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) {    = [];      for ($i =0; $i < $number; $i + +)        {= 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, We loop the current time into the $data inside
    3. forThe loop executes and returns the $data .

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

$result // Here we call the function we created above foreach ($resultas$value) {    sleep(1);   This pauses for 1 seconds, and we follow a useful    echo$value. ' <br/> ';}

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

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

Think of a problem

We notice that when the function createrange is called, the value of the $number is 10, a small number. suppose, now pass a value 10000000 (10 million).

so, in the function createrange , the for loop needs to be executed 1000 thousands of Times. And there are 1000 thousands of values placed inside the $data , and the $data array is placed in 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+ +)        {time();    }}

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

Using the generator

Let's run the second piece of code again:

$result // Here we call the function we created above foreach ($resultas$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 the result of sleep(1) . But why is there no interval for the first time? That's because:

    • When the generator is not used: the for loop result within the createrange function is quickly placed in the $data and returned immediately. so, the foreach loop is a fixed array.
    • When using the Generator: the value of Createrange is not a one-time fast build, but relies on a foreach loop. the foreach loop is once and for executes Once.

here, you should have a clue to the Generator.

In-depth understanding of generator code anatomy

Let's dissect the code just NOW.

functionCreaterange ($number){     for($i= 0;$i<$number;$i++) {yield time(); }}$result= Createrange (10);//Here we call the function we created aboveforeach($result  as $value){    Sleep(1); Echo $value.‘ <br/> ';}

Let's restore the code execution process.

  1. First call the createrange function, Pass in the parameter 10 , but the for value executes once and then stops, and tells the value that the foreach first loop can use.
  2. foreach begins the loop on the $result , comes in first to sleep(1) , and then starts using a For-given value to perform the Output.
  3. foreach prepares the second loop and, before starting the second loop, it requests the For loop Again.
  4. The For loop then executes again, telling the resulting timestamp to foreach .
  5. foreach gets the second value, and the Output. Because of the sleep(1) in foreach , 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 memory is always the value of a loop, no matter how large the $number is starting to pass in, 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 what is the foreach loop in the code? In fact, PHP will return an object of the Generator class when it uses the Generator. foreach iterates over the object, and every iteration, PHP calculates the next value that needs to be iterated through the Generator instance. This way, foreach will know the value of the next Iteration.

also, it stops immediately after the for loop executes in the Run. Wait for the next loop of foreach again and for the next value to be requested, the 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");functionreadtxt () {#code ...    $handle=fopen("./test.txt", ' RB ');  while(feof($handle)===false) {        #code ...Yieldfgets($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.

This article was reproduced from 1190000012334856

Performance optimizations that are ignored in php: 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.