, The more abstract layers of the program, the stricter the separation of the abstract layers, the lower the program efficiency.
The most primitive php program mode applied to web pages is the script embedding mode. That is, the php script is embedded by adding identifiers to the places where a Web page needs to dynamically process or display data. Generally, this is the earliest Learning Mode for php programmers. It has only one abstraction layer, namely the web page. Therefore, this article calls it a single-layer mode.
As the website grows, programmers may find it difficult to maintain programs in the single-layer mode. When you want to modify or expand the functions of a program, you may find that the code is very messy and you cannot start. As a result, the template class was born, which made a webpage composed of two files: a php program file and an html template file. Common Template classes include the Template class in the PHPLib Library and the Smarty Template class. With the addition of an additional processing program (Template Class), the program efficiency is reduced. If you do not believe it, test it yourself. In fact, in general, functions (the most primitive programming method) are more efficient than functions (process-oriented), and functions are more efficient than object encapsulation (Object-Oriented. Therefore, even in the compilation language, it is necessary to use C to write efficiently, instead of C ++, such as the kernel of the FreeBSD operating system. In the case of extreme efficiency, it is necessary to write in a sink.
In order to allow the program to adapt to multiple database systems or to easily convert the database system at any time, a class is often used to encapsulate the functions dealing with the database, in this way, you only need to replace the encapsulation class when converting the database system, and the main program does not need to be modified. Here, another class is used, and the efficiency is reduced.
The above template class divides the program into two abstract layers: The program layer and the presentation layer. The application of database classes divides the program layer into the data interface layer and data processing layer.
The larger the project, the more abstraction layers that need to be separated, which makes the division of labor clear and convenient for management, but at the cost of program execution efficiency.
To reduce the efficiency caused by the abstraction layer, there are two optimization methods: reduce the abstraction layer and optimize the interfaces between the abstraction layer. Generally, the abstraction layer should not be blindly reduced to improve efficiency, which will make the code messy and difficult to manage. However, you should not create too many abstraction layers for a small project unless you have plans to do a lot in the future. This article does not discuss how to properly split the abstraction layer in depth.
For the two layered examples mentioned above, the interfaces between the optimized abstraction layer are template classes and database operation classes. Abstract layer interfaces need to be frequently called in programs to exchange information between different layers. Therefore, layer interfaces are worthy of optimization. Database Interface classes may only encapsulate some database functions, but there is little room for optimization. There is a lot of room for optimization for template classes. Generally, the more common the Template model is, the more powerful the Template class is and the lower the efficiency is. For example, the Template class in the PHPLib library has great room for optimization. Compared with the PHPLib Template, the Smarty Template is more complex. I have never used it. It is said that there is a cache mechanism and I do not know whether it can make up for its performance loss. Next let's take a look at how many things of the PHPLib Template class can be optimized.
(1) When reading template files, the file function is inefficient. Instead, use the get_file_content function.
(2) When matching the sub-template, the regular expression replacement function preg_replace is inefficient. Instead, use the str_pos function to locate and use the str_replace function to replace the sub-template. This optimization method will be analyzed in detail later.
(3) The template model is highly versatile and can adapt to various situations. However, the efficiency of common methods may be very low in terms of handling specific details. You can modify the template model as needed. My approach is to create a relatively general template class, and then assign a template class that only applies to a specific program. Some optimizations can be made on the Template model of the general Template class (compared with the PHPLib Template). For example, it is complicated to process two-dimensional data tables with the PHPLib Template, the class method needs to be called multiple times (essentially a function call). Therefore, the function of processing two-dimensional data tables can be encapsulated into an efficient method to avoid multiple calls of the method.
(4) The debugging function is not required for small projects and all Code related to debugging is removed.
After I overwrite the template class at the above four points, the execution time of a complex page is reduced by an order of magnitude (no optimizations except the template ).
Optimize the interfaces between the abstract layers of your program, especially when these interfaces use ready-made functions or classes. Because these functions or classes are designed to adapt to the general situation at the expense of some efficiency, and their authors may not consider efficiency issues. The efficiency of such a famous PHPLib template class is not necessarily high.
2. Detailed code optimization
(1) As mentioned above in template optimization, regular expression matching is much slower than string matching. Try to use string matching instead of regular expression matching. Sometimes, although regular expression matching makes the program code more concise, and general string matching makes the code more redundant, string matching is still more efficient than regular expressions in many cases.
(2) string replacement functions str_replace and preg_replace can both accept array parameters. Sometimes you need to replace strings in batches, it is more efficient to use array parameters than to call the replacement function cyclically. For example, the following code:
For ($ I = 0; $ I <$ n; $ I ++ ){
$ Str = str_replace ($ search [$ I], $ replace [$ I], $ str );
}
Should be replaced:
$ Str = str_replace ($ search, $ replace, $ str );
Note: $ search and $ replace are both arrays.
For the array usage of str_replace and preg_replace, see the PHP manual.
(3) For conditional statements used for value assignment, use? : Operator
Here is only three detailed code optimization methods. In fact, PHP programs still have a lot of code optimization methods. To master these methods, you need to read the PHP manual and learn more about functions. When different functions are used for different combinations to solve some detailed problems, different methods are generated. The actual efficiency test should be performed on different methods to obtain the optimization method.
3. object-oriented, process-oriented, class, function, and macro
Although object-oriented methods have many advantages in programming (not listed here), the execution efficiency of object-oriented programs is generally inferior to process-oriented, an obvious reason is that object-oriented programs often need to frequently call object methods to make the code concise and clear, but reduce the program execution efficiency.
For small and medium-sized projects, it is best to think about program efficiency. object-oriented and process-oriented projects are both designed to work with classes, functions, and Macros in code. Here we mention a concept that may be unfamiliar to readers-macro ). There are Macros in C language and Macros in macro compilation, but PHP does not officially define the concept of "macros. However, we can use the require and include functions to implement macro functions. Require and include are usually used to include files such as function libraries or class libraries in program code. They are rarely used to directly include program code files, because the inclusion of program code sometimes reduces the ease of coding. When a piece of code needs to be executed on many pages, it is often considered to be packaged as a function or encapsulated as a class. However, this method has the following Disadvantages:
(1) Reduce program efficiency. Because function/class method calls are added.
(2) Sometimes this segment of embedded code is complicated, and the implementation function is not simple. The blocking function does not conform to the simple function principle.
(3) Sometimes the embedded code needs to exchange a large amount of data with the outside. If the function is enclosed, the parameter table is large and the return value of the processing function becomes complex.
(4) due to the two shortcomings above (2) (3), changes to the interfaces of functions or classes may become troublesome when the data exchanged between embedded code and external code changes.
In this case, we recommend that you use macros to directly write the embedded code to the included files for the pages to contain. However, it is necessary to clearly comment out macro calling methods, input and output data, and so on, to make up for the reduction of code accessibility.
In short, object-oriented, process-oriented, class, function, and macro should all be used in combination based on actual conditions, and certain principles should not be blindly adhered.
4. SQL database
Originally, SQL database optimization should not be classified as PHP optimization. However, in actual applications, PHP often works with SQL database to build websites. Common databases include MySQL and PostgreSQL. Therefore, the efficiency of SQL queries directly affects the efficiency of PHP programs. Therefore, this article also focuses on it.
(1) In MySQL, InnoDB or bdb tables (supporting transactions) are less efficient than MyISAM tables (not supporting transactions), especially InnoDB tables are much less efficient than MyISAM tables, the main disadvantage of bdb tables is that they occupy more disk space than MyISAM tables, and cannot check the disk space occupied by each table. For small and medium-sized applications, the probability of data inconsistency is very small, so you can use the MyISAM table to improve efficiency.
(2) properly create indexes and store redundant data. This topic is too big to be detailed in this article.
(3) Some SQL queries only need to know whether there are qualified rows in the database, so you only need to find a row and the search will end. Therefore, you can add limit 1 at the end of the SQL statement so that the database does not search any rows that meet the conditions.
(4) Try to use less join. Some inefficient join queries can be avoided by storing redundant data.
(5) Sometimes it is necessary to compare the time gap between the current time and the time of a column in the database, and return the rows with the time gap meeting certain conditions. Before MySQL 4.1, there was no datediff function, but you can use the date_add or date_sub function to implement it in a concise manner. For example, to return rows with the xtime column more than 10 days ago, there are two ways to write:
Method 1:
Select somecolumn from sometable where date_add (xtime, interval 10 day) <now ()
Method 2:
Select somecolumn from sometable where date_sub (now (), interval 10 day)> xtime
The execution results of the two statements are equivalent but the efficiency is different. If the xtime column has an index, the method 1 statement cannot use the index, and the method 2 statement can use the index. Therefore, the method 2 should be used to improve the efficiency.
5. Delayed output and Buffering
Sometimes some pages cannot be optimized to the desired speed. In this case, you can consider using the latency output and buffering technology.
Buffer is also a big topic, so this article does not intend to detail it, but it is a brief introduction.
Common technologies include the caching technology of Web service software, such as Apache Buffer technology, and dynamic script Buffer technology, for example, the buffer technology implemented by PHP programming.
In addition, it can be divided into static buffer technology and Dynamic Buffer technology. Static buffering technology stores static html pages generated by Dynamic Content on disks. The client is basically dealing with static pages, and the whole website is like a static website. When appropriate, the server background calls dynamic programs to update static content (regenerate static content ). The Dynamic Buffer technology means that the client is still dealing with dynamic pages. When a dynamic page receives a request from the customer, it first checks whether there is a buffer page. If yes, it directly outputs the static page to the client, if no or the cache page is out of date, the cache page is regenerated and output to the client.