Table of Contents
您可能感兴趣的文章:
Home Backend Development PHP Tutorial Performance optimization tools in PHP that you may overlook: Generator-related content

Performance optimization tools in PHP that you may overlook: Generator-related content

Jul 06, 2018 pm 05:51 PM
php performance optimization php website performance optimization

Performance optimization is an essential part of our development. The following article mainly introduces you to the performance optimization tool in PHP that you may overlook: the relevant information of the generator. The article introduces it in great detail through example code. Friends in need can refer to it, let’s take a look below.

Preface

If you are a Python or other language developer, 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.

Under what circumstances will you encounter PHP performance problems?

1: Improper use of PHP syntax.

2: Use the PHP language to do things it is not good at.

3: The service connected using PHP language is not powerful.

4: PHP’s own shortcomings (things that PHP itself can’t do).

5: A problem we don’t know about either? (To explore, analyze and find solutions and improve the level of development).

Advantages


  • # Pique 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.

Concept introduction

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;
}
Copy after login

This is a very common PHP function that we often use when processing 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.

After the for loop is executed, $data Go back out.

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.&#39;<br />&#39;;
}
Copy after login

Let’s take a look at the running results in the browser:



It's perfect here, no problems whatsoever. (Of course you can’t see the effect of sleep(1))

Think about a question

We noticed that when calling the function createRange The value passed to $number is 10, a very small number. Suppose, now pass a value of 10000000 (10 million).

Then, in the function createRange, the for loop needs to be executed 10 million times. And 10 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();
 }
}
Copy after login
Look at this code that is very similar to just now. We deleted the array $data and did not return anything. Instead, we used a keyword yield before time()

Using the generator

Let’s run the second piece of code again:

$result = createRange(10); / / Here we call the function we created above

foreach($result as $value){

sleep(1);

echo $value.'
';

}## ################We miraculously discovered 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 the createRange function is quickly placed in $data and returned immediately. Therefore, the foreach loop is a fixed array. ############When using a generator: the value of createRange is not generated quickly at once, but depends on the foreach loop. foreach loops once and for is executed once. ############At this point, you should have some idea about the generator. ############In-depth understanding of the generator##################Code analysis############Let’s follow 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.'
'; }
Copy after login
######### Let’s restore the code execution process. ###
  • 首先调用createRange函数,传入参数10,但是for值执行了一次然后停止了,并且告诉foreach第一次循环可以用的值。

  • foreach开始对$result循环,进来首先sleep(1),然后开始使用for给的一个值执行输出。

  • foreach准备第二次循环,开始第二次循环之前,它向for循环又请求了一次。

  • for循环于是又执行了一次,将生成的时间戳告诉foreach.

  • foreach拿到第二个值,并且输出。由于foreach中sleep(1),所以,for循环延迟了1秒生成当前时间

所以,整个代码执行中,始终只有一个记录值参与循环,内存中也只有一条信息。

无论开始传入的$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", &#39;rb&#39;);

 while (feof($handle)===false) {
  # code...
  yield fgets($handle);
 }

 fclose($handle);
}

foreach (readTxt() as $key => $value) {
 # code...
 echo $value.&#39;<br />&#39;;
}
Copy after login


通过上图的输出结果我们可以看出代码完全正常。

但是,背后的代码执行规则却一点儿也不一样。使用生成器读取文件,第一次读取了第一行,第二次读取了第二行,以此类推,每次被加载到内存中的文字只有一行,大大的减小了内存的使用。

这样,即使读取上G的文本也不用担心,完全可以像读取很小文件一样编写代码。

总结

您可能感兴趣的文章:

Laravel框架中composer自动加载的实现详解

PHP服务端环境搭建的图文教程

php实现希尔排序算法的方法讲解

The above is the detailed content of Performance optimization tools in PHP that you may overlook: Generator-related content. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Performance optimization techniques for developing and implementing Baidu Wenxinyiyan API interface using PHP Performance optimization techniques for developing and implementing Baidu Wenxinyiyan API interface using PHP Aug 26, 2023 pm 10:39 PM

Performance optimization techniques for using PHP to develop and implement Baidu Wenxin Yiyan API interface. With the popularity of the Internet, more and more developers use third-party API interfaces to obtain data to enrich their application content. Baidu Wenxin Yiyan API interface is a popular data interface. It can return a random inspirational, philosophical or warm sentence, which can be used to beautify the program interface, increase user experience, etc. However, when using the Baidu Wenxinyiyan API interface, we also face some performance considerations. API call speed

How to standardize performance optimization through PHP code specifications How to standardize performance optimization through PHP code specifications Aug 11, 2023 pm 03:51 PM

How to standardize performance optimization through PHP code specifications Introduction: With the rapid development of the Internet, more and more websites and applications are developed based on the PHP language. In the PHP development process, performance optimization is a crucial aspect. A high-performance PHP code can significantly improve the website's response speed and user experience. This article will explore how to standardize performance optimization through PHP code specifications and provide some practical code examples for reference. 1. Reduce database queries. Frequent database queries are a common feature during the development process.

PHP 7 performance optimization tips: How to use the isset function to determine whether a variable has been declared PHP 7 performance optimization tips: How to use the isset function to determine whether a variable has been declared Aug 01, 2023 am 08:27 AM

PHP7 performance optimization tips: How to use the isset function to determine whether a variable has been declared Introduction: In PHP development, we often need to determine whether a variable has been declared. This is particularly important in situations such as when using an undeclared variable that produces an error. In PHP7, for performance optimization reasons, we should try to use the isset function to determine whether a variable has been declared, instead of directly using functions such as empty and is_null. Why use isset: In PHP

How to Optimize Website Performance and Loading Speed ​​with PHP How to Optimize Website Performance and Loading Speed ​​with PHP Sep 12, 2023 am 10:13 AM

How to use PHP to optimize website performance and loading speed With the rapid development of the Internet, website performance and loading speed have attracted more and more attention. As a widely used server-side scripting language, PHP plays an important role in optimizing website performance and loading speed. This article will introduce some tips and methods for using PHP to improve the performance and loading speed of your website. Using a caching mechanism Caching is an effective way to improve website performance. PHP provides a variety of caching mechanisms, such as file caching, memory caching and data caching.

How to use PHP for performance optimization and tuning How to use PHP for performance optimization and tuning Aug 02, 2023 pm 09:40 PM

How to use PHP for performance optimization and tuning In the process of developing web applications, performance optimization and tuning are important tasks that cannot be ignored. As a popular server-side scripting language, PHP also has some techniques and tools that can improve performance. This article will introduce some common PHP performance optimization and tuning methods, and provide sample code to help readers better understand. Using cache caching is one of the important means to improve the performance of web applications. You can reduce access to the database and reduce IO operations to improve performance by using cache. make

How to improve PHP performance in high concurrency environments How to improve PHP performance in high concurrency environments Aug 11, 2023 pm 07:30 PM

Summary of how to improve the performance of PHP in high-concurrency environments: With the development of Internet technology, more and more websites and applications need to handle a large number of concurrent requests. For systems that use PHP as a back-end development language, performance optimization in high-concurrency environments is particularly important. This article will introduce some methods to improve the performance of PHP in high concurrency environments, including code optimization, cache usage and database optimization. 1. Code optimization and choosing the appropriate PHP framework: Choosing the appropriate PHP framework can improve the development efficiency and performance of the system.

Performance Optimization Guide for PHP Product Inventory Management System Performance Optimization Guide for PHP Product Inventory Management System Aug 17, 2023 am 08:29 AM

Performance Optimization Guide for PHP Product Inventory Management System As the e-commerce industry continues to develop and grow, in the face of huge product inventory data and increasing user visits, the performance requirements for the product inventory management system are getting higher and higher. In PHP development, how to optimize the product inventory management system and improve the performance and response speed of the system is a very important issue. This article will introduce some common performance optimization techniques and give corresponding code examples to help developers better understand and apply them. Database performance optimization 1.1. Using indexes

Optimize your code: PHP performance tips Optimize your code: PHP performance tips Jun 05, 2023 am 08:21 AM

In actual development, in order to achieve better performance and higher scalability of a website or application, the optimization of PHP code is a very important step. Here are some PHP performance tips to help your code run faster. 1. Minimize function calls and variables 1.1 Function calls Function calls have a great impact on the performance of PHP code, because each function needs to allocate space in memory. When writing PHP code, you should try to avoid too many function calls and use inline functions or custom functions instead. 1.2 Variables

See all articles