PHP some ways to improve website performance

Source: Internet
Author: User
Tags apc compact website performance

The previous time interview asked this question, the answer is not very comprehensive, went to ask the degree Niang, got some relatively full answer, because more source can not determine the original source. Here's the answer to sharing.

First, large-scale website performance improvement strategy:

Large Web sites, such as portals, have a basic solution in the face of massive user access and high concurrent requests: the use of high-performance servers, high-performance databases, high-efficiency programming languages, and high-performance web containers. These solutions to some extent imply a greater investment.

A web container is a service program that has a program that provides services on one port of the server, and this program handles requests from clients, such as the Tomcat container in Java, which is a container for ASP IIS or PWS. A server can have multiple containers.

1. Static HTML

In fact, we all know that the most efficient, the least expensive is the pure static HTML page, so we try to make the page on our site using static pages to achieve, the simplest method is actually the most effective method.

2, Image server separation

You know, for the Web server, whether it is Apache, IIS or other containers, the picture is the most consumption of resources, so we have to separate the picture and the page, which is basically a large web site will adopt the strategy, they have independent, and even many of the picture server. Such architectures can reduce the pressure on the server system that provides page access requests and ensure that the system does not crash due to picture problems.

In the application server and picture server, can be different configuration optimization, such as Apache in the configuration of contenttype can be as little as possible to support, as few loadmodule, to ensure higher system consumption and execution efficiency.

3, database cluster, library table hash

Large Web sites have complex applications, which must use databases, and in the face of a large number of accesses, the bottleneck of the database can soon be revealed, when a database will soon be unable to meet the application, so we need to use the database cluster or library table hash.

In the context of database clustering, many databases have their own solutions, and the common master/slave provided by MySQL is a similar scenario.

Clusters typically use CDN with GSBL and DNS load Balancing technology, a group of foreground servers in each region, for example: NetEase, Baidu uses DNS load balancing technology, a set of front servers per channel, a search using DNS load technology, all channels share a group of foreground server cluster.

Library table hashing is a common and most effective solution.

We install the business and application in the application or function module to separate the database, different modules corresponding to different databases or tables, and then according to a certain policy on a page or function of a smaller database hash, such as the user table, according to user ID for the table hash, This makes it possible to improve the performance of the system at a low cost and has a good scalability.

Sohu Forum is the use of such a framework, the Forum users, settings, posts and other information database separation, and then to the post, the user in accordance with the plate and ID hash database and table, finally can be configured in the configuration file simple configuration will allow the system at any time to add a low-cost database to supplement the system performance.

4. Cache

The word cache has been touched by technology, and caches are used in many places. Caching in the Web site architecture and Web development is also very important. Here we first describe the two most basic caches. The advanced and distributed caches are described later.

Architecture cache, people familiar with Apache can know that Apache provides its own cache module, can also use the addition of Squid module for caching, both of which can effectively improve the access response of Apache.

Web application development cache, the memory cache provided on Linux is a common cache interface, can be used in web development, such as Java development can call MemoryCache to some data caching and communication sharing, some large communities use such a framework. In addition, in the use of web language development, all kinds of languages have their own cache modules and methods, PHP has pear cache module, Java more,. NET is not very familiar with, I believe there is certainly.

5. Mirror

Mirroring is often used by large web sites to improve performance and data security, the mirror technology can solve the different network access providers and geographical user access speed differences, such as the difference between chinanet and edunet prompted a lot of websites in the education network to build mirror site, Data is scheduled to be updated or updated in real time.

6. Load Balancing

Load balancing will be a high-end solution for large web sites that address high-load access and a large number of concurrent requests.

Load balancing technology has developed for many years, there are many professional service providers and products can be selected, I personally contacted a number of solutions, including two architecture can give you a reference

Second, the PHP Code writing optimization:

1. Echo is much faster than print.

Two methods will print something on the page, but Echo does not return any value, and print will return 0 or 1 if it succeeds or fails.

2. Include_once is more time-consuming than include .

Because it needs to check if the class you want to include is already included.

3. Be sure to use single quotation marks instead of double quotes for long paragraph strings .

Because double quotes go to search for variables in a string. For example: Echo ' This is a long string '. $name is much faster than echo "This is long string $name".

4. Do not nest in loops using a For loop

5. If the function can be defined as a static

Then do not define a member function, the static function is 33% faster than the member function.

6. If you can solve the problem without passing regular expressions

Then don't use the regular. Regular expressions are slower than PHP-native functions.

For example use (Discount net http://dazhes.com) str_replace replace Preg_replae.

7. Try not to include files with relative paths

Locate the file in the relative path, find it in the current directory, and then look in turn. This is very slow to find files. It is best to define constants such as Web_root, and then use this constant to include the file.

8. Equal sign = = = = = = Faster than equals = =

And if (1 = = ' 1′) will return true,if (0 = = ") will also return true, and when you use the congruent symbol when the IF (1 = = = ' 1′) and if (0===") will return false. So it's best to use the congruent notation when you need to detect some Boolean variables in your program.

Third, there are several ways for thinkphp

1. Turn off debug mode

Because the debug mode is turned off, the project compilation cache is automatically generated and the log write is turned off, which can reduce the overhead of many IO loads and log writes.

2. Turn on page compression output

Starting with version 3.1, the Output_encode configuration parameter was added to control page compression output.

3. Turn on caching

Installing an APC or XCache cache in a Web site deployment environment can effectively improve the performance and memory footprint of your website

XCache is an open source opcode cache/optimizer, which means that he can improve PHP performance on your server. By buffering the compiled PHP data to shared memory to avoid a repetitive compilation process, he is able to use the buffer-compiled code directly to speed up. You can typically increase your page generation rate by 2 to 5 times times, reducing server load.

Alternative PHP cache (APC) is a valid open source Cache tool for PHP that caches opcode PHP intermediate codes.

4. Field Cache

By default, the field cache is generated automatically, and after development is done, the database becomes less volatile, so you can consider merging the fields to cache the corresponding model classes, which reduces the IO overhead for each read of the field cache. The merge method is to find the corresponding field cache file under Runtime/data/_fields

Iv. Database Optimization

1. Choose the right storage engine

In MySQL, for example, there are two storage engines MyISAM and InnoDB, each with a few pros and cons.

MyISAM is suitable for applications that require a large number of queries. The InnoDB trend will be a very complex storage engine, and for some small applications it will be slower than MyISAM. However, it supports "row locks" and supports transactions.

2. Optimize the data type of the field

Remember a principle, the smaller the column the faster. For most database engines, hard disk operations can be the most significant bottleneck. So it's very helpful to have your data compact, because it reduces access to the hard drive.

If a table has only a few columns (for example, a dictionary table, a configuration table), then we have no reason to use INT to master the keys, using Mediumint, SMALLINT or smaller TINYINT will be more economical. If you don't need to record time, using date is much better than DATETIME. Of course, you also need to leave enough room for expansion.

3. Add an index to the search field

The index does not necessarily give the primary key or the unique field. If you have a field in your table that you will always use to do a search, it is best to index it, unless the field you are searching for is a large text field, you should create a full-text index.

4. Avoid using SELECT * to read more data from the database, the query becomes slower. And, if your database server and Web server are two separate servers, this also increases the load on the network transport. Even if you want to query all the fields of the data table, try not to use the * wildcard character, the use of the built-in provided field exclusion definition may be able to bring more convenience .

5. Use ENUM instead of VARCHAR

The ENUM type is very fast and compact. In fact, it holds the TINYINT, but it appears as a string on its appearance. In this way, using this field to make a list of options becomes quite perfect. For example, the values for these fields, such as gender, ethnicity, department, and status, are limited and fixed, so you should use ENUM instead of VARCHAR.

6. Use not NULL as much as possible

Unless you have a very special reason to use null values, you should always keep your fields not NULL. Null actually requires extra space, and your program will be more complex when you compare it. Of course, this is not to say that you cannot use NULL, the reality is very complex, there will still be cases where you need to use a null value.

7, fixed-length table will be faster

If all the fields in the table are fixed length, the entire table is considered "static" or "Fixed-length". For example, there are no fields of the following type in the table: Varchar,text,blob. As long as you include one of these fields, the table is not a fixed-length static table, so the MySQL engine will handle it in a different way.

Fixed-length tables can improve performance because MySQL searches faster because these fixed lengths are easy to calculate the offset of the next data, so the nature of reading will be fast. And if the field is not fixed, then every time you want to find the next one, you need the program to find the primary key.

Also, fixed-length tables are more likely to be cached and rebuilt. However, the only side effect is that a fixed-length field wastes some space, because the field is set to allocate so much space whether you use it or not.

Using the "vertical split" technique, you can split your table into two that are fixed-length and one that is indefinite.

8, Vertical segmentation "vertical segmentation" is a database of tables by column into a few tables, which can reduce the complexity of the table and the number of fields, so as to achieve optimization purposes.

For example, there is a field in the user table that is a home address, which is an optional field, and you do not need to read or rewrite this field frequently in addition to your personal information when working in a database. So, why not put him in another table? This will make your table better performance, we think is not, a lot of time, I for the user table, only the user ID, user name, password, user role, etc. will be used frequently. A smaller table will always have good performance.

In addition, you need to note that these separated fields form the table, you do not regularly join them, otherwise, this performance will be worse than not split, and, it will be a drop of magnitude.

9, EXPLAIN your SELECT query;

Use the EXPLAIN keyword to let you know how MySQL handles your SQL statements. This can help you analyze the performance bottlenecks of your query statement or table structure. EXPLAIN's query results will also tell you how your index primary key is being leveraged, how your data tables are searched and sorted ... Wait, wait.

In general, we can add the keyword explain to the previous SELECT statement that is more complex, especially when it comes to multiple tables. You can use phpMyAdmin to do this. See annex Explain.doc for details.

v. Optimization of the former segment

After optimizing the backend and the database, what we have to do is to optimize your front-end pages and resource files for the output page, mainly including the optimization of pictures, JS, and style files.

We recommend that the following Web performance testing tools be used for testing and analysis, with recommendations for optimization:

Pagespeed tools developed by Google

Site administrators and network developers can use Pagespeed to evaluate the performance of their pages and get advice on how to improve performance.

YSlow YSlow

You can analyze the page of your site and tell you how to optimize it based on certain rules to improve your site's performance.

PHP some ways to improve website performance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.