Home Backend Development PHP Tutorial PHP junk code optimization operation code_PHP tutorial

PHP junk code optimization operation code_PHP tutorial

Jul 21, 2016 pm 03:34 PM
mysql php superior host code optimization company exist Rubbish operate Serve server of website USA virtual

The company has several websites hosted on virtual hosts in the United States. The mysql service on the server suddenly hangs up almost every day, and then recovers after a while. It is suspected that it has exceeded the CPU usage limit and was automatically terminated. But there is actually very little traffic on this server. So I contacted the Indian Asan customer service of the server provider earlier to see if other users had caused too many problems and caused everyone to die. After searching, the Asans swore to pat their hairy chests to ensure that they were not theirs. Problem, things are not resolved. It's not a problem, so I had to check it myself. Fortunately, I can access the information_schema library. After looking it up, I'm speechless. The data in user_statistics shows that one of our mysql users has extremely high busy_time, cpu_time and other indicators. Fortunately, Ah San didn't notice it. So I quickly checked the program. The previous website program was not made by me, but I knew that there were many problems in it, ranging from architecture to implementation. However, there were not so many pages as usual. The code was mixed with HTML. I couldn’t die after looking at it all. (This kind of At that time, I especially felt how wonderful MVC was), and it was enough to just run it normally, since there was not much traffic anyway.

Since mysql has a heavy burden, let’s find this first. Make a local mirror of the website and run it. Modify and add

Copy code The code is as follows:
[mysqld]
log="d:/temp/mysql.log"
log_slow_queries="d:/temp/ mysql_slow.log"
long_query_time=1


This directory must already exist. Restart the mysql service and you can record.

After checking the sql records, I was surprised. The number of queries was astonishing. On any page, there were dozens of sql queries, and as many as thousands!

Take the forum as an example, the number of database queries for a page is only 10 times, and it can be even lower if cache is used. Calculating it this way, it’s equivalent to dozens of times the original burden. How can we not worry about it?

No one has the perseverance to write down hundreds of queries, so it must be a circular query. The sql statement also shows this. Once you know the reason, it’s easy to change it. Find the relevant page and change the loop query. For example, there is a page that wants to display all regional categories and the number of articles under this category. Ignore the structural optimization of the database. As far as the program is concerned, it turns out that It probably looks like this

Copy code The code is as follows:
$sql1="SELECT aid,count(*) as cc FROM pz_content WHERE uid=$uid group by aid";
$rs1=$db->query($sql1);
if(is_array($rs1)){
foreach($rs1 as $r1){
Output...
echo id2name($r1->aid);
}
}
............
function id2name($aid)
{
$sql="select ename from pz_area_a where aid_a=".$id;
$result=mysql_query($sql);
$row=mysql_fetch_object( $result);
return $row->ename;
}

Regardless of the fault tolerance of the code, you will know from the implementation that he first read the user's relevant articles and The regions are grouped and counted according to region ID, and then the region name is output for each region. Therefore, if there are 10,000 regions, 10,000 queries will be needed here. I put a timing code and looked at it. It consumes about 6M of memory, takes 16 seconds to execute, and has a total of 1001 queries

In fact, this is something that can be done with just one sentence of SQL, and no loop is required. .


Copy code The code is as follows:
$sql1="select pz_area.aid,pz_area.ename,tb1. cc from pz_area right join (SELECT aid,count(*) as cc FROM pz_content WHERE uid=$uid group by aid) as tb1 on pz_area.aid=tb1.aid";
$rs1=$db->query ($sql1);
if(is_array($rs1)){
foreach($rs1 as $r1){
Output...
echo $r1->ename;
}
}


The problem will be solved. After re-running, the memory consumption is almost the same. For one query, the CPU execution time is only 647 milliseconds, which is 26 times worse than the original! Looking at it again, I found that the pz_content table has quite a lot of records. There are often queries and divisions by region, but it turns out there is no index. By adding an index to aid, the execution time is reduced to 432 milliseconds.

Forget about this page, let’s stop here and continue next time.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322364.htmlTechArticleThe company has several websites hosted on virtual hosts in the United States. The mysql service on the server suddenly fails almost every day. When did it hang up and then recover after a while, I suspect it was beyond...
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
What are the top ten digital currency trading app platforms? The top ten digital currency exchange platforms What are the top ten digital currency trading app platforms? The top ten digital currency exchange platforms Apr 22, 2025 pm 02:54 PM

Top 10 digital currency trading app platforms: 1. OKX, 2. Binance, 3. Gate.io, 4. Huobi, 5. Coinbase, 6. Kraken, 7. Bitfinex, 8. KuCoin, 9. Bybit, 10. Bitstamp, these platforms provide real-time market trends, technical analysis tools and user-friendly interfaces to help investors conduct effective market analysis and trading decisions.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How does MySQL differ from Oracle? How does MySQL differ from Oracle? Apr 22, 2025 pm 05:57 PM

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

See all articles