1 origin
With regard to PHP, many people intuitively feel that PHP is a flexible scripting language with rich library classes, simple to use, and secure. It is very suitable for WEB development, but its performance is low. Is PHP performance really as bad as everyone feels? This article focuses on this topic. In-depth analysis of PHP performance problems from the source code, application scenarios, benchmark performance, comparative analysis, and other aspects, through real performance data to identify the key factors affecting the performance of the PHP module.
2. Analysis of PHP performance based on principles
The Principle Analysis of PHP performance mainly involves memory management, variables, functions, operating mechanisms, and network models.
2.1 Memory Management
Similar to Nginx memory management, PHP is also based on the memory pool internally and introduces the concept of the lifecycle of the memory pool. In terms of the memory pool, PHP manages PHP scripts and all extended memory-related operations. The management of large and small memory uses different implementation methods and optimizations. For details, refer to the following documents: http://www.laruence.com/2011/11/09/2277.html. During the lifecycle of memory allocation and recovery, PHP uses an initialization application + dynamic expansion + Memory ID collection mechanism, and directly re-creates a mask for the memory pool after each request.
2.2 Variables
PHP is a language of the weak variable type. Therefore, in PHP, all PHP variables correspond to a type of Zval, which is defined as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560621S-0.jpg "/>
Figure 1. PHP Variables
In terms of variables, PHP has done a lot of optimization work, such as the Reference counting and copy on writer mechanisms. This ensures Optimization of memory usage and reduces the number of memory copies, see the http://blog.xiuwz.com/2011/11/09/php-using-internal-zval ). In terms of arrays, PHP uses efficient hashtable internally.
2.3 Functions
In PHP, all PHP functions are converted into an internal function pointer. For example, extended functions
ZEND_FUNCTION (my_function); // similar to function my_function (){}
After being expanded internally, it will be a function.
Void zif_my_function (INTERNAL_FUNCTION_PARAMETERS );
Void zif_my_function (
Int ht,
Zval * return_value,
Zval * this_ptr,
Int return_value_used,
Zend_executor_globals * executor_globals
);
From this perspective, the PHP function also corresponds to a function pointer internally.
2.4 Operating Mechanism
When talking about PHP performance, many people will say that "C/C ++ is a compilation type, JAVA is a semi-compilation type, and PHP is an interpreted type ". That is to say, PHP performs dynamic parsing before code execution. From this perspective, PHP performance must be poor.
Indeed, the output from the PHP script is indeed a process of dynamic parsing and code execution. Specifically, the PHP script running mechanism is shown in:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560CH9-1.jpg "/>
Figure 2. PHP Running Mechanism
PHP is also divided into three stages:
● Parse. Syntax analysis stage.
● Compile. Compile and generate the opcode intermediate code.
● Execute. Running, dynamic running for output.
We can also see that there is a compilation process in PHP itself. In fact, this feature is basically used in standard production environments, such as opcode cache tools apc, eacc, and xcache. Based on opcode cache,PHPThe script is compiled once and run multiple times.. From this point on, PHP and JAVA semi-compilation mechanisms are very similar.
Therefore, from the perspective of the operating mechanism, the PHP running mode is very similar to that of JAVA, which generates intermediate Codes first and then runs on different virtual machines.
2.5 Dynamic Operation
From the above analysis, PHP has done a lot of work in terms of memory management, variables, functions, and operating mechanisms. Therefore, from the perspective of principle,PHPThere should be no performance problems, and the performance should at least be consistent with JAVARelatively close.
But why do many people still feel that PHP is slow? In particular, some computational performance comparison, the total found that PHP processing performance is relatively inefficient http://shootout.alioth.debian.org/u32/php.php ). At this time, we have to talk about the performance problems caused by the characteristics of PHP Dynamic Language. Because PHP is a dynamic runtime, therefore, all variables, functions, object calls, and scope implementations are identified in the execution phase. This fundamentally determines something that is hard to change in PHP performance:InC/C ++And other variables and functions that can be determined in the static compilation stage.It needs to be determined in the dynamic operation, which determines the PHPThe intermediate code cannot run directly and must run on Zend Engine.Upper.
Speaking of the specific implementation of PHP variables, I have to say another thing: hashtable. Hashtable can be said to be one of the soul of PHP. It is widely used in PHP, including variable symbol stack and function symbol stack. It is based on hashtable.
Take the PHP variable as an example to illustrate the dynamic running characteristics of PHP, such as the Code:
- <?php
-
- $var = “hello, blog.xiuwz.com”;
-
- ?>
-
The execution result of this Code is to add an item in the variable symbol stack as a hashtable.
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560A2S-2.jpg "/>
When this variable is used, it is used to search for the variable in the stack, that is, a hash query process is performed for the variable call ).
Similarly, for function calls, there is basically a function symbol stack hashtable ).
In fact, the characteristics of dynamic variable search can also be seen in the PHP operating mechanism. PHP Code is interpreted and compiled in the following process:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560AU4-3.jpg "/>
Figure 3. PHP running instance
As you can see, PHP code after compile produces the Class symbol table, function symbol table, and OPCODE. During actual execution, zend Engine searches and processes the corresponding symbol table based on the op code.
To some extent, it is difficult to find a solution to this problem. This is determined by the dynamic characteristics of the PHP language. However, many domestic and foreign users are looking for solutions. In this way, PHP can be completely optimized. A typical column is facebook's hiphop (https://github.com/facebook/hiphop-php ).
However, all such compilation optimization solutions sacrifice the dynamic running characteristics of PHP. Of course, some compromise can be made on the Dynamic Features in the specific compilation optimization, but it is difficult to achieve full compatibility.
2.6 Network Model
Currently, PHP is used. The ideal and common mode is fastcgiPHP-FPM ). The Network Model of Php-fpm is similar to nginx and adopts the multi-process Master + Multi-worker mode. Php-fpm is based on the epoll model in libevent. From the network model perspective, this method does not have performance differences with other network models.
2.7 conclusion
According to the above analysis, there is no obvious performance difference in the basic memory management, variables, functions, operating mechanisms, and network models. However, due to the dynamic running characteristics of PHP, it determines the CPU overhead and extra memory overhead of all variable search and function running in PHP compared with other compiled languages, it can be obtained through subsequent benchmark performance and comparative analysis.
Therefore, it can be seen that PHP is not suitable for some scenarios: a large number of computing tasks, operations on large data volumes, and applications with strict memory requirements. If you want to implement these functions, you are also recommended to implement them through extension, and then provide the hook function for PHP to call. This reduces the overhead of variable and Function Series in internal computing.
3 benchmark performance
Standard Data is missing for PHP benchmark performance. Most people have a perceptual knowledge. Some people think that QPS is the limit of PHP. In addition, there is no authoritative number to respond to the performance of the framework and the impact of the framework on the performance.
The purpose of this section is to provide a benchmark reference performance indicator and give you an intuitive understanding of the data.
The specific benchmark performance includes the following aspects:
1. Bare PHP performance. Complete basic functions.
2. Performance of the bare framework. Only the simplest route distribution is required and core functions are used.
3. benchmark performance of the standard module. The benchmark performance of a standard module refers to the benchmark performance with complete service module functions.
3.1 Environment Description
Test environment:
Uname-
Linux db-forum-test17.db01.baidu.com 2.6.9 _ 5-7-0-0 #1 SMP Wed Aug 12 17:35:51 CST 2009 x86_64 x86_64 x86_64 GNU/Linux
Red Hat Enterprise Linux AS release 4 (Nahant Update 3)
8 Intel (R) Xeon (R) CPU E5520 @ 2.27 GHz
Software related:
Nginx:
Nginx version: nginx/0.8.54 built by gcc 3.4.5 20051201 (Red Hat 3.4.5-2)
Php5: using php-fpm)
PHP 5.2.8 (cli) (built: Mar 6 2011 17:16:18)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
With eAccelerator v0.9.5.3, Copyright (c) 2004-2006 eAccelerator, by eAccelerator
Bingo2:
PHP framework.
Other Instructions:
Deployment method of the target machine:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1356061941-4.jpg "/>
Script.
The stress testing machine and the target machine are deployed independently.
3.2 bare PHP Performance
The simplest PHP script.
- <?php
-
- require_once ‘./actions/indexAction.php’;
-
- $objAction = new indexAction();
-
- $objAction->init();
-
- $objAction->execute();
-
- ?>
-
The code in Acitons/indexAction. php is as follows:
- <?php
-
- class indexAction
-
- {
-
- public function execute()
-
- {
-
- echo ‘hello, world!’;
-
- }
-
- }
-
- ?>
-
The test results by using the stress tool are as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1356062557-5.jpg "/>
3.3 bare PHP framework performance
To compare with 3.2, similar functions are implemented based on the bingo2 framework. The Code is as follows:
- <?php
-
- require_once ‘Bingo/Controller/Front.php’;
-
- $objFrontController = Bingo_Controller_Front::getInstance(array(
-
- ‘actionDir’ => ‘./actions’,
-
- ));
-
- $objFrontController->dispatch();
-
- ?>
-
The stress test results are as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560B423-6.jpg "/>
The test results show that:Although the framework has a certain amount of consumption, it has a very small impact on the overall performance..
3.4 benchmark performance of the standard PHP Module
The so-called standard PHP module refers to the basic functions required by a PHP module:
● Route distribution.
● Automatic loading.
● LOG initialization & Notice LOG printing. Therefore, all the UI requests have a standard log.
● Handle errors.
● Time correction.
● Automatically calculates the time consumption of each stage.
● Encoding recognition & encoding conversion.
● Parsing and calling of standard configuration files
Use the bingo2 code automatic generation tool to generate the standard test PHP module: test.
The test results are as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560AW0-7.jpg "/>
3.5 conclusion
From the conclusion of the test data, the PHP performance is still acceptable. The benchmark performance can reach thousands or even hundreds of thousands of QPS. As to why the performance in most PHP modules is poor, we should find out the bottleneck of the system at this time, rather than simply saying OK, PHP is not good, so let's change to C. In the next chapter, we will use some examples to compare and use C to deal with the problem)
The following conclusions can be drawn from the benchmark data:
1. PHP has good performance. Simple functions can reach qps50cpu IDLE), the limit can also exceed W.
2. the PHP framework has very limited impact on performance. Especially when there is a certain amount of business logic and data interaction, it can be ignored.
3. A standard PHP module with benchmark performance up to qps80 cpu idle ).
Performance Comparison and Analysis of 4PHP and C
Most of the time, when you find that the PHP module has poor performance, you can say "OK, let's rewrite it with C ". In the company, the use of C/C ++ to write business logic modules is everywhere. In the past few years, almost all of them were written using C. At that time, what we wrote was really painful: difficult debugging and agile.
In this section, we will talk about the performance comparison between the business logic written in C and the business logic module written in PHP, and use real data to speak.
4.1 prerequisites
Why is this premise especially true? In ideal cases, a function is implemented in PHP, and the performance cannot be better than that written in ideal C. Pay special attention to this premise.
But why do we need to compare them? In reality, how many excellent C programs can be written and completely high performance can be achieved with frequent modifications? And in real applications, is the performance of C really better than PHP? There is no definite data for demonstration.
Therefore, the comparison in this chapter is based on the actual situation and uses real data to speak.
4.2 Introduction to real business module PHP module vs c Module 4.2.1 Business Module
In a real case column, the traffic of this business module is as high as billions. The architecture of this module is as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1356064363-8.jpg "/>
Figure 4 business module Architecture
This business module provides simple functions. The upper layer is web server, and the downstream is each data module. Data interaction is based on socket. The main working model of this business module is:ResponseWeb serverAccording to the request, read the corresponding data from each backend data module, and generate the final HTMLThe page is returned to the webServer.
To facilitate the subsequent introduction, define CUI to indicate the modules implemented by C, and PHPUI to indicate the modules implemented by PHP.
4.2.2C/C ++ module performance data results
In, a new C/C ++ framework was selected for restructuring the module. At the time of reconstruction, the number of backend Data Modules connected by this moduleIn5-7Items.
Based on the C/C ++ module, the final test data is divided into two parts:
1. performance comparison test.
Tests the performance of real data based on the current online pressure. Therefore, only one stress data is tested as follows:
Pressure: 210QPS
CPUIDLE): 84.18
Ii. Ultimate Performance Test 1.
The test model is as follows: CUI connects only one core data module, and other data modules are completely disabled.
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560B154-9.jpg "/>
Iii. Ultimate Performance Test 2.
The test model is as follows: CUI is connected to a core data module and three data modules at the backend. Other data modules are not connected.
The performance data after the test is as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560B2O-10.jpg "/>
4.2.3 performance test data of the PHP implementation module
In the past 11 years, the CUI based on the year 09 has basically reached the point where code is not maintained. At this time, the ultimate performance of CUI is no longer enough.600QPSThe main reason is that with the development of the project, the number of backend data modules has increased to 14 ). Therefore, we decided to adopt the PHP Solution to rewrite the entire module and generate the final pbui module.
The performance test results are divided into two types:
1. php UI connects to a core module. The test data is as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1356063132-11.jpg "/>
Figure 5. PHPUI Performance Test Result 1
2. php UI connects 14 backend modules ). The test performance data is as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1356063324-12.jpg "/>
Figure 6. PHPUI Performance Test Result 2
4.2.4 data comparison conclusion
Because the business logic and test methods of PHPUI and CUI are not exactly the same, some points of physical comparison are extracted for sorting. The comparison data is as follows:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1356064b1-13.jpg "/>
From the comparison data above,In real business projects,PHPUIThe performance is no better than that of CUI.Difference. This is not simply verified by a single module. In the department, many of our modules are migrated from C/C ++ to PHP. According to the migration results, there is no qualitative performance degradation, and the performance indicators after most modules are migrated are very close.
At this time, we need to think about why it is like this? Segmentation has two problems:
1. Why isn't PHPUI performance much worse than CUI in real business projects?
2. Why is the benchmark PHP performance so high that QPS can only be QPS in 80 CPUs?
In fact, these two problems can also be attributed to one reason:In real business projects, performance is more influenced than the language used, but the business-related part, suchSocketInteractions, such as string processing and network interaction Package Size.
OK. The next key is to find out the key factors that affect performance.
4.2.5 key factors affecting PHP module performance
From the above analysis, we can conclude that the key factor affecting the performance of the front-end PHP module is not that the language itself is PHP, JAVA, or C ). So what are the key factors that affect the performance of the PHP business module? CPU consumption is one of the key points to measure the performance of a project, considering that a series of logs are printed in the system. By analyzing the time consumption distribution of requests in logs, we can see the key points.
In our system, the CPU time consumption focuses on the following aspects:
1. Total Request time.
2. Performance of key functions requested. All socket interactions are time-consuming.
3. template rendering is also a key aspect of good deeds.
In the previous analysis, we basically determined that socket and string processing are one of the key points. We can verify the data. Extract a specified number of logs from a module and perform comprehensive analysis to obtain the following data:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/13560615X-14.jpg "/>
From this we can see that in a business module, the most influential is socket data interaction, followed by a large number of string processing. The specific subdivision includes the following factors: socket interaction count, socket interaction package size, socket interaction response time, and string processing.
4.2.6 conclusion
Through the above analysis, we can draw the following conclusion: In the front-end business module, the PHP language itself will not become a performance bottleneck. The key factors that affect performance are:
● Number of network interactions.
● The size of network interaction data, including the overhead of data package and unpackage.
● Network interaction response time.
● Massive string processing.
5 final conclusion
Through the specific analysis of the above three chapters, we can draw the following conclusions:
1. From the perspective of PHP implementation principles, PHP is a semi-compiled language, and a lot of optimization work is carried out in all aspects, so there will be no obvious performance problems. However, due to the characteristics of Dynamic Language, PHP needs to run on the Zend Engine virtual machine, and requires additional overhead in Variable Search, function call, and scope switch.
2. From the benchmark performance of PHP, PHP itself will not have significant resource consumption, and the single-host QPS will be able to easily surpass W. The PHP framework itself will not have a critical impact on the performance of the business system.
3. In actual application scenarios, modules implemented based on C language are not much more efficient than modules implemented based on PHP. In actual application scenarios, more performance overhead lies in Network Data Interaction and string processing. Slight differences in language performance will not become a bottleneck.
Therefore, it can be launched: most business systems based on the C language can be considered to be migrated to PHP. On the one hand, it can be developed quickly, and on the other hand, performance will not be affected.
Finally, for a detailed analysis of the key factors affecting PHP performance and a comparative analysis of the benchmark performance of language function-level PHP and C, please pay attention to the following "in-depth discussion of PHP performance issues".
6. References
Http://yanbin.org/
Https://wiki.php.net/internals/zend_mm
Http://blog.xiuwz.com/2011/11/09/php-using-internal-zval/
Http://developers.facebook.com/blog/post/358/
Https://github.com/facebook/hiphop-php
By xuliqiang
This article first in: Search R & D department official blog] http://stblog.baidu-tech.com /? P = 1343 follow Baidu technology salon]
This article from "Baidu technology blog" blog, please be sure to keep this source http://baidutech.blog.51cto.com/4114344/742971