When I first wrote Python, I was familiar with generators as a way to optimize memory performance, but many phpers probably didn’t know about generators, either because they were introduced in PHP 5.5 or because they weren’t obvious. However, the generator functionality is really useful. Recently in writing CSV import and export, need to deal with a lot of data, thought of PHP generator, write a summary

advantages

The advantages of generators are as follows:

  • Generators can have a significant impact on the performance of PHP applications
  • PHP code saves a lot of memory when running
  • Better for computing large amounts of data

Concept is introduced

First, let’s put the concept of generators behind us and look at a simple PHP function:

function rangeNum($num){
    $data = [];
    for($i=0; $i<$num; $i++){ $data[] = time(); }return $data;
}
Copy the code

This is a very simple PHP function that we use a lot when dealing with some array logic. The code here is also very simple.

Let’s write another function to fetch the data from $data

$data = rangeNum(10);
foreach($data as $value){
    sleep(1);
    echo $value.'<br />';
}
Copy the code

It’s perfect. There’s no problem.

Think about:

When we pass 1000W or more when calling a function, the 1000W data in the for loop will be stored in memory when calling the function, which will occupy a lot of memory

Creating a generator

We modify the function directly

function rangeNum($num){
    for($i=0; $i<$num; $i++){yieldtime(); }}Copy the code

Using generators

$data = rangeNum(10);
foreach($data as $value){
    sleep(1);
    echo $value.'<br />';
}
Copy the code

At this point, you should have some idea of generators.

Conceptual understanding

First, to clarify the concept: the yield keyword of a generator is not a return value. The technical term for it is output value. It just produces a value

Actual development and application

Reading large files

A lot of PHP development involves reading large files, like CSV files, Excel files, or some log files. If these files are really, really big, like 20 gigabytes. At this point, it is not practical to simply read everything into memory for processing at once.

Millions of page views

Yield generators have been around since PHP5.5, and yield provides a simpler way to implement simple iterators with significantly less performance overhead and complexity than the way classes implement Iterator interfaces.

The article ends with

All articles are original and handwritten, please point out any mistakes.