Powerful performance optimization tools you may ignore in PHP: generators and powerful performance optimization tools

Source: Internet
Author: User
Tags php language

Powerful performance optimization tools you may ignore in PHP: generators and powerful performance optimization tools

Preface

If you are a Python or other language partner, you should be familiar with generators. However, many PHP developers may not know the generator function. It may be because the generator is a function introduced by PHP 5.5.0, or the generator does not play a significant role. However, the generator function is indeed very useful.

Under what circumstances will PHP performance problems occur?

1: PHP syntax usage is inappropriate.

2: PHP is used to do things that it is not good.

3: services connected using the PHP language are not powerful.

4: Short Board of PHP itself (something PHP itself can't do ).

5: We don't know either? (Explore and analyze solutions to improve the development realm ).

Advantages

It is estimated that you will still be confused when talking about the concept directly. So let's talk about the advantages first, which may arouse your interest. Which of the following are the advantages of the generator:

  • The generator will have a great impact on the performance of PHP applications.
  • Saving a lot of memory during PHP code running
  • Suitable for computing large amounts of data

Then, how exactly are these magical functions implemented? Let's give an example.

Concept Introduction

First, let go 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, which is often used when processing arrays. The code here is also very simple:

  • Create a function.
  • The function contains a for loop, which puts the current time in $ data.
  • After the for loop is executed, $ data is returned.

The following is not complete. Let's continue. Let's write another function to print the return value of this function cyclically:

$ Result = createRange (10); // call the previously created function foreach ($ result as $ value) {sleep (1); // pause for 1 second, echo $ value will be used later. '<br/> ';}

Let's look at the running result in the browser:

This is perfect and there is no problem. (Of course, sleep (1) You cannot see the effect)

Think about a problem

We noticed that when calling the createRange function, the value of $ number is 10, a small number. Assume that a value of 10000000 (10 million) is passed ).

In the createRange function, the for loop needs to be executed for 10 million times. In addition, there are 10 million values in $ data, while the $ data array is in memory. Therefore, calling a function occupies a large amount of memory.

Here, the generator can be used.

Create a generator

We directly modify the code. observe the following:

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

Let's take a look at this code. We deleted the array $ data and didn't return any content. Instead, we used the yield keyword before time ().

Use Generator

Run the second code:

$ Result = createRange (10); // call the function we created above
Foreach ($ result as $ value ){
Sleep (1 );
Echo $ value. '<br/> ';
}


We miraculously discovered that the output value is different from the one that didn't use a generator for the first time. The value (timestamp) is separated by 1 second.

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

  • If no generator is used, the for loop result in the createRange function is saved to $ data and returned immediately. Therefore, the foreach loop is a fixed array.
  • When using the generator: the value of createRange is not generated at a time, but depends on the foreach loop. Foreach repeats once and for executes once.

Here, you should have a clue about the generator.

Deep understanding of Generators

Code profiling

Next we will analyze the code.

Function createRange ($ number) {for ($ I = 0; $ I <$ number; $ I ++) {yield time ();}} $ result = createRange (10); // call the foreach ($ result as $ value) {sleep (1); echo $ value. '<br/> ';}

Let's restore the code execution process.

  • First, call the createRange function and input the parameter 10, but the for value is executed once and then stopped, and tells foreach the value that can be used in the first loop.
  • Foreach starts the $ result loop. First, sleep (1) is entered, and then an output is executed using a value given by.
  • Foreach prepares the second loop. Before the second loop starts, it requests again to the for loop.
  • The for loop is executed again, and the generated timestamp is told to foreach.
  • Foreach gets the second value and outputs it. Due to sleep (1) In foreach, The for loop delay is 1 second to generate the current time

Therefore, during code execution, there is always only one record value involved in the loop, and there is only one message in the memory.

No matter how large the $ number is, the memory is always a cyclic value because it does not generate all result sets immediately.

Concept understanding

At this point, you should have understood what a generator is. The following describes the generator principle.

First, define a concept: the generator yield keyword is not the return value. His specialized term is output value, which only generates a value.

So what is the foreach loop in the code? In fact, when PHP uses a Generator, it will return an object of the Generator class. Foreach can iterate on this object. every iteration, PHP calculates the value to be iterated next time through the Generator instance. In this way, foreach will know the value to be iterated next time.

In addition, after running the for loop, it stops immediately. When foreach asks for the next value with for again in the next loop, the for Loop will be executed again, and then immediately stops again. The execution ends until the condition is not met.

Practical Application Development

Many PHP developers do not know about generators, but they do not understand the application field. So what applications does the generator have in actual development?

Read large files

PHP developers often need to read large files, such as csv files, text files, or some log files. If these files are large, for example, 5 GB. In this case, it is unrealistic to directly read all the content to the memory at one time.

The generator can be used here. Let's look at an example: Reading text files

Create a text document and input several lines of text to read the document.

<?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 />';}


The output result shows that the code is completely normal.

However, the code execution rules are not the same at all. When the generator is used to read the file, the first line is read for the first time, the second line is read for the second time, and so on. Each time the text loaded into the memory is only one line, the memory usage is greatly reduced.

In this way, you don't have to worry about reading G text, and you can write code just like reading small files.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.