Table of Contents
Cause
Turnaround
Performance Optimization
Summary
Home Topics php mysql Create a MySQL index to greatly optimize the performance of a PHP application

Create a MySQL index to greatly optimize the performance of a PHP application

Dec 29, 2022 pm 04:21 PM
php

This article brings you relevant knowledge about mysql, which mainly introduces the relevant content about indexing to greatly optimize the performance of a PHP application. Let's take a look at it together. I hope it will be helpful to everyone.

Create a MySQL index to greatly optimize the performance of a PHP application

Cause

A friend of mine was going to do a project two months ago, and for the purpose of rapid online promotion, he directly purchased a company’s Source code and let the seller deploy it online. After seeing the source code, I directly said to my friend: I have been cheated. The quality of this source code is a bit poor, and there may be serious performance problems when the number of users is increased.

I have a basis for making such an evaluation:

  • As a near-real-time application, the core code is written in PHP, and the concurrency of many scenarios is controlled through database table records. And repeated requests;

  • PHP development is not a problem, but the other engineer does not seem to know that there is a CLI mode, but uses scheduled tasks (crontab) to achieve non-stop running of the program, so it is so vast Dozens of curl scheduled tasks are executed every minute;

  • There are many class1.php and class1-1.php files in the code. It is difficult to know their existence at a glance. Purpose;

  • There are a lot of codes for looping to read the database, and the naming rules are confusing.

Of course, code that can make money is good code (the other party makes money through these codes), so I don’t worry about it too much. The initial thought was that with a 4-core 8G configuration, it would be difficult to serve 10,000 customers, but 5,000 would be enough.

Turnaround

Just this week, I suddenly received frequent alarm text messages and emails from Alibaba Cloud, saying that the CPU usage was too high. Do you think that the marketing promotion is going well and the number of users has increased significantly? When I asked my friends, there were less than 300 users!

Create a MySQL index to greatly optimize the performance of a PHP application

#At this time, I realized that the actual performance of this code was worse than I thought, and there were serious performance problems. According to this resource consumption rate, upgrading hardware is a bottomless pit, and performance optimization is the right way.

Performance Optimization

It has been two months since I got the code. I occasionally look at it in my spare time and already have a general understanding of its structure and main functions. Now that we have serious performance issues, it's time to try some performance optimizations.

In view of the fact that dozens of scheduled tasks are running continuously and continuously drive the system operation, the related functions of scheduled tasks are the first to be understood. Based on my own understanding, I first suspended more than twenty planned tasks that were no longer needed. After pausing useless scheduled tasks, the overall system CPU usage dropped to more than 60%, and the annoying reminder text messages and emails finally stopped. After waiting for a day, my friends did not report that the functions were affected, which shows that the idea and starting point are correct.

But with more than 200 users consuming resources like this, there must be something wrong. I logged into the server again when I was free today, executed the top command, and found that the mysql process has been occupying more than 200% of the CPU resources. After reading the source code, I know that there is a reason for MySQL's high usage and it is possible, but I still want to see why it consumes so many resources.

Log in to the MySQL server and check whether the slow log is enabled: show variables like '%slow%'; and find that the slow query log is enabled:

Create a MySQL index to greatly optimize the performance of a PHP application

Continue Check the log and find that a certain SQL statement has always appeared in the log:

Create a MySQL index to greatly optimize the performance of a PHP application

You can see that more than 380,000 rows of records were scanned when this SQL statement was executed. One of the two tables involved in the statement has more than 600 records, and the other has more than 40,000 records. This is equivalent to scanning the entire table with more than 40,000 records several times. No wonder it is extremely slow.

Then check the indexes of the two tables. Except for the auto-incremented id as the primary key, no other indexes are created. Use explain to execute the statement, which shows that no index is used:

Create a MySQL index to greatly optimize the performance of a PHP application

Next, create indexes on the uid and session_id columns of the query conditions on the two tables. After the index creation is completed, the visible CPU usage and system load are reduced. Use explain again to execute the query statement. The index information has been used and the number of scanned rows has been greatly reduced:

Create a MySQL index to greatly optimize the performance of a PHP application

After the above optimization, the current overall CPU usage of the application is 5% Around 15%, MySQL's CPU usage dropped from 4 to 0.3. Finally, there is no need to worry about performance issues for the time being. Even if the server configuration is reduced to 1 core CPU, it can still sustain it.

Further check the code and combine it with the logs to create indexes and modify some query statements. The CPU usage dropped to about 6%. Finally, we don’t have to worry about performance issues for the time being

Summary

In development projects, engineers must not only write "usable" code, but also "easy to use" code. In this example, by creating two indexes, the system performance can be greatly improved, which is to change the code from "usable" to "easy to use".

The performance optimization mentioned in this article focuses on operation and maintenance, and the performance optimization in the code has not been touched yet. But a general principle is correct: use more cache and reduce synchronous reads from slow IO devices as much as possible.

Recommended learning: "mysql video tutorial", "PHP video tutorial"

The above is the detailed content of Create a MySQL index to greatly optimize the performance of a PHP application. 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles