An overlooked performance optimization tool in PHP: generators
In this article, we will share with you the knowledge of the neglected performance optimization tool in PHP: the generator, hoping to help everyone. 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
If I talk about the concept directly, I guess you will still be confused after listening to it, so let’s talk about the advantages first, maybe it can arouse your interest. So what are the advantages of generators, as follows:
Generators will have a very large impact on the performance of PHP applications
PHP code runtime Save a lot of memory
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<p>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: </p><ol class=" list-paddingleft-2"> <li><p>We create a function. </p></li> <li><p>The function contains a <code>for</code> loop. We loop the current time into <code>$data</code></p></li> <li><p><code>for</code>After the loop is executed, <code>$data</code> is returned. </p></li> </ol><p> 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: </p><pre class="brush:php;toolbar:false">$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 problems 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 the 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<p>Look at this code that is very similar to just now, we deleted the array<code>$ data</code>, and nothing is returned, but a keyword is used before <code>time()</code><code>yield</code></p><h2 id="Use-generator">Use generator</h2><p> Let’s run the second piece of code again: </p><pre class="brush:php;toolbar:false">$result = createRange(10); // 这里调用上面我们创建的函数 foreach($result as $value){ sleep(1); echo $value.'<br>'; }
We miraculously discovered that the output value is the same as the first time it was generated without using The device is different. 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:
foreachcreateRange
The result of thefor
loop within thecreateRange
function is quickly placed in$ data
and returns immediately. Therefore, loops through a fixed array. -
forWhen using a generator: The value of
createRange
is not generated quickly at one time, but relies on theforeach
loop.foreach
loops once and 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'; }
- Let’s restore the code execution process.
-
foreachFirst call the
createRange
function, passing in the parameter10
, but thefor
value is executed once and then stops, And tell the values that can be used in the first loop. -
A value given by forforeach
Start the loop on$result
, come in firstsleep(1)
, and then start using executes the output. -
forforeach
prepares for the second loop. Before starting the second loop, it requests the loop again. -
foreachfor
The loop is then executed again, and the generated timestamp is told to . -
forforeach
Get the second value and output it. Sincesleep(1)
inforeach
, the loop is delayed by 1 second to generate the current time
无论开始传入的$number
有多大,由于并不会立即生成所有结果集,所以内存始终是一条循环的值。
概念理解
到这里,你应该已经大概理解什么是生成器了。下面我们来说下生成器原理。
首先明确一个概念:生成器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的文本也不用担心,完全可以像读取很小文件一样编写代码。
相关推荐:
The above is the detailed content of An overlooked performance optimization tool in PHP: generators. For more information, please follow other related articles on the PHP Chinese website!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.