


Detailed explanation of the neglected performance optimization tool in PHP: generator
If you are working in Python or other languages, you should be familiar with generators. But many PHP developers may not know the generator function. It may be because the generator is a function introduced in PHP 5.5.0, or it may be that the function of the generator is not very obvious. However, the generator function is really useful.
Advantages
I guess you will still be confused after listening to the concept directly, so let’s talk about the advantages first, maybe it can arouse your interest. So what are the advantages of the generator, as follows:
- The generator will have a great impact on the performance of the PHP application
- Save a lot of memory when the PHP code is running
- More suitable for calculating large amounts of data
So, how are these magical functions achieved? Let's give an example first.
Introduction to the concept
First of all, let’s put 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 are dealing with It is often used when working with some arrays. The code here is also very simple:
- We create a function. The
- function contains a
for
loop. We loop the current time into$data
-
for
loop After execution is completed,$data
is returned.
It’s not over yet, let’s continue. Let’s write another function and print out the return value of this function in a loop:
$result = createRange(10); // 这里调用上面我们创建的函数 foreach($result as $value){ sleep(1);//这里停顿1秒,我们后续有用 echo $value.'<br />'; }复制代码
Let’s take a look at the running results in the browser:

It’s perfect here, no issues whatsoever. (Of course sleep(1)
you can’t see the effect)
Think about a question
We noticed that when calling the function createRange
The passed value of $number
is 10, a very small number. Suppose, now pass a value 10000000
(10 million).
Then, in function createRange
, the for
loop needs to be executed 1000
times. And 1000
million values are placed in $data
, and the $data
array is placed in memory. Therefore, a lot of memory will be occupied when calling functions.
Here, the generator can show its talents.
Create generator
We modify the code directly, please pay attention:
function createRange($number){ for($i=0;$i<$number;$i++){ yield time(); } }复制代码
Look at this code that is very similar to just now, we deleted the array$ data
, and nothing is returned, but a keyword is used before time()
yield
Use generator
Let’s run the second piece of code again:
$result = createRange(10); // 这里调用上面我们创建的函数 foreach($result as $value){ sleep(1); echo $value.'<br />'; }复制代码

We miraculously Found that the output value is different from the first time without using the generator. The values (timestamps) here are separated by 1 second.
The one second interval here is actually the consequence of sleep(1)
. But why is there no gap the first time? That's because:
- When the generator is not used: The
for
loop result in thecreateRange
function is quickly placed in$data
and return immediately. Therefore,foreach
loops through a fixed array. - When using a generator: The value of
createRange
is not generated quickly at once, but relies on theforeach
loop.foreach
loops once andfor
executes once.
At this point, you should have some idea about the generator.
In-depth understanding of the generator
Code analysis
Let’s analyze the code just now.
function createRange($number){ for($i=0;$i<$number;$i++){ yield time(); } } $result = createRange(10); // 这里调用上面我们创建的函数 foreach($result as $value){ sleep(1); echo $value.'<br />'; }复制代码
Let’s restore the code execution process.
- First call the
createRange
function, passing in the parameter10
, but thefor
value is executed once and then stops, and tellsforeach
Values that can be used in the first loop. -
foreach
Start the loop on$result
, come in firstsleep(1)
, and then start usingfor
A value performs output. -
foreach
prepares for the second loop. Before starting the second loop, it requests thefor
loop again. -
for
The loop is executed again, and the generated timestamp is told toforeach
. -
foreach
to get the Two values and output. Sincesleep(1)
inforeach
, thefor
loop is delayed by 1 second to generate the current time
So, the entire code During execution, there is always only one record value participating in the loop, and there is only one piece of information in the memory.
No matter how big the $number
is initially passed in, since not all result sets are generated immediately, the memory is always a loop of values.
Conceptual understanding
At this point, you should have a rough understanding of what a generator is. Let’s talk about the generator principle below.
首先明确一个概念:生成器yield关键字不是返回值,他的专业术语叫产出值,只是生成一个值
那么代码中foreach
循环的是什么?其实是PHP在使用生成器的时候,会返回一个Generator
类的对象。foreach
可以对该对象进行迭代,每一次迭代,PHP会通过Generator
实例计算出下一次需要迭代的值。这样foreach
就知道下一次需要迭代的值了。
而且,在运行中for
循环执行后,会立即停止。等待foreach
下次循环时候再次和for
索要下次的值的时候,for
循环才会再执行一次,然后立即再次停止。直到不满足条件不执行结束。
实际开发应用
很多PHP开发者不了解生成器,其实主要是不了解应用领域。那么,生成器在实际开发中有哪些应用?
读取超大文件
PHP开发很多时候都要读取大文件,比如csv文件、text文件,或者一些日志文件。这些文件如果很大,比如5个G。这时,直接一次性把所有的内容读取到内存中计算不太现实。
这里生成器就可以派上用场啦。简单看个例子:读取text文件

我们创建一个text文本文档,并在其中输入几行文字,示范读取。
<?php header("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 />'; }复制代码

通过上图的输出结果我们可以看出代码完全正常。
但是,背后的代码执行规则却一点儿也不一样。使用生成器读取文件,第一次读取了第一行,第二次读取了第二行,以此类推,每次被加载到内存中的文字只有一行,大大的减小了内存的使用。
这样,即使读取上G的文本也不用担心,完全可以像读取很小文件一样编写代码。
想了解更多编程学习,敬请关注php培训栏目!
The above is the detailed content of Detailed explanation of the neglected performance optimization tool in PHP: generator. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
