This is a summary afterwards. After going through many pitfalls in the tuning process, we finally perfected and implemented a preliminary performance testing plan, and summarized some practical skills in the Laravel development process through real test data.
0x00 Origin
Recently, a colleague reported that the response of the application written in Laravel is a bit slow, and more than 20 concurrency runs the CPU full... In order to solve the slow problem, even some interfaces use nodejs Come and write.
And my first reaction was how could a popular framework be so bad? There must be something wrong with the use. In order to find out, I started this Laravel application performance tuning journey.
0x01 Tuning Tips
The optimization techniques used in this performance test plan are mainly based on the Laravel framework itself and the tools it provides.
Turn off application debug
app.debug=false
Cache configuration information
php artisan config:cache
Cache routing information
php artisan router:cache
- ##Class map loading optimization
php artisan optimize
- Automatic loading optimization
composer dumpautoload
- Only load necessary middleware as needed
- Use a just-in-time compiler (JIT), such as: HHVM, OPcache
- Use PHP 7.x
APP_DEBUG=false2. Cache configuration information
php artisan config:cache
Run the above command to merge all the configuration information in the config folder into a bootstrap/cache/config.php file. Reduce the number of files loaded at runtime.
php artisan config:clearRun the above command to clear the cache of configuration information, that is, delete the
bootstrap/cache/config.php file
php artisan route:cache
Running the above command will generate the file bootstrap/cache/routes.php. Route caching can effectively improve the router's registration efficiency, and the effect is more obvious in large applications.
php artisan route:clearRunning the above command will clear the routing cache, which means deleting the
bootstrap/cache/routes.php file.
php artisan optimize --force
Running the above command can merge commonly loaded classes into one file, improving operating efficiency by reducing the loading of files. This command will generate two files bootstrap/cache/compiled.php and
bootstrap/cache/services.json.
config/compile.php file.
--force The parameter file can also be automatically generated.
php artisan clear-compiledRunning the above command will clear the class mapping loading optimization, that is, delete the two files
bootstrap/cache/compiled.php and
bootstrap/cache/services.json .
composer dumpautoload -o
Laravel applications are built using composer. This command will convert PSR-0 and PSR-4 into a class mapping table to improve class loading speed.
Note: This operation has already been done in the6. Load only necessary middleware as neededThe Laravel application has a lot of middleware built in and enabled. Every Laravel request loads related middleware and generates various data. Commenting out unnecessary middleware (such as session support) inphp artisan optimize --force
command.
app/Http/Kernel.php can greatly improve performance.
Well, limited to your real enterprise environment, this may not change for a long time, so I didn’t mention it.0x02 Test PlanWe use a simple Apache ab command to test only the application entry file, and record and analyze the data.
- Only test the application’s entry file index.php, and access “/” or “/index.php” to return to the welcome page of the framework. More comprehensive performance testing requires testing of more interfaces of the application.
- Use the Apache ab command.
ab -t 10 -c 10 {url}
. This command means to initiate 10 requests to the url at the same time and last for 10 seconds. The specific parameter settings in the command need to be selected based on the server performance to be tested.
- In order to avoid data errors caused by machine fluctuations, each test condition will execute the ab command multiple times and record the command execution results, focusing on the number of requests processed per second and the request response time. , analyze and eliminate outliers.
Every time the test conditions are adjusted, you need to access the welcome page on the browser to ensure that there are no access errors due to the modification of the test conditions. If page access errors occur, the test results will be incorrect.
Server environment description
All test data divorced from the specific environment is meaningless, and comparisons can only be made under similar conditions.
This environment runs on a Mac with 8G memory, 2.8GHz processor, and SSD hard drive.
The test server is built using Homestead. The virtual machine is configured with a single-core CPU and 2G memory.
The server PHP version is 7.1. If not specified, OPcache is turned on.
The Laravel application tested was written in version 5.2. There are 85 routes defined in
app\Http\routes.php
.During the test process, except for the virtual machine, terminal and fixed browser window, there are no programs that will affect the operation of the machine.
The above data can be referred to when you conduct your own testing.
0x03 Test process and data
1. No optimization has been done
1.1 Operation
Perform the corresponding check items according to the following operate.
Run
ab -t 10 -c 10 http://myurl.com/index.php
Basic check items
APP_DEBUG=true
does not exist in the .env file
bootstrap/cache/config.php
does not exist
bootstrap/cache/routes.php
No There are
bootstrap/cache/compiled.php
andbootstrap/cache/services.json
##app/Http/Kernel.php
Most of the middleware is enabled in
- Browser access the Laravel application welcome page to ensure normal access
- Based on step 1 Modify
APP_DEBUG=false
in the .env file.
- Visit the Laravel application welcome page with your browser to ensure normal access.
- Run
ab -t 10 -c 10 http://myurl.com/index.php
.
##2.3 Comparison results
Compare with the results of step 1 Discovery: After turning off application debugging, the number of requests processed per second increased from 26-34 to 33-35, and the request response time dropped from mostly more than 300ms to about 290ms.
The effect is not obvious, but there is indeed a certain improvement.Note: This part is closely related to the usage of logs in the application.
3. Enable cache configuration information
3.1 Operation
- Based on step 2, run
- php artisan config:cache
, confirm the generation of
bootstrap/cache/config.php
. Visit the Laravel application welcome page with your browser to ensure normal access. - Run
- ab -t 10 -c 10 http://myurl.com/index.php
.
3.2 Data record
##3.3 Comparison results
The effect is not obvious, but there is indeed a certain improvement.
4. Enable cache routing information
4.1 Operation##Based on step 3, run
php artisan route:cache- , confirm the generation of
- bootstrap/cache/routes.php
.
Visit the Laravel application welcome page with your browser to ensure normal access.
-
Run
ab -t 10 -c 10 http://myurl.com/index.php . 4.2 Data record
##4.3 Comparison resultsCompare with the results of step 3 Discovery: After turning on the routing information cache, the number of requests processed per second increased from 36-38 to about 60, and the request response time dropped from 260ms to about 160ms. The effect was significant. From the perspective of TPS, it increased by 70%.
5.1 Operation
Based on step 4, comment out unnecessary middleware code.- Visit the Laravel application welcome page with your browser to ensure normal access.
- Run
ab -t 10 -c 10 http://myurl.com/index.php
.
Note: I commented out all the middleware in this test. In actual situations, you should try to keep only necessary middleware.
5.2 Data record
The effect is very obvious. From the perspective of TPS, it has increased by 50%.
6. Turn on class map loading optimization6.1 Operation- Based on step 5, run
php artisan optimize - -force
, confirm the generation of
bootstrap/cache/compiled.phpand
bootstrap/cache/services.json.
- Visit the Laravel application welcome page with your browser to ensure normal access.
- Run
ab -t 10 -c 10 http://myurl.com/index.php
.
##6.3 Comparison results
Compare with the results of step 5 Discovery: After optimizing class mapping loading, the number of requests processed per second increased from 90 to 110, and the request response time dropped from 110ms to less than 100ms. The
effect is quite obvious.7. Close OPcache
7.1 Operation
- Based on step 6, close PHP’s OPcache and restart the server. Confirm that OPcache is closed via phpinfo()'s Zend OPcache.
- Visit the Laravel application welcome page with your browser to ensure normal access.
- Run
- ab -t 10 -c 10 http://myurl.com/index.php
.
7.2 Data record
##7.3 Comparison results
Turning OPcache on and off, the data is actually several times different.
After that, I reopened PHP’s OPcache and the data was restored to the level of step 6.
1. [LogicException] Unable to prepare route [/] for serialization. Uses Closure.Running0x04 Pitfalls
php The artisan route:cache
command reports this error.Cause: Closure is used when processing "/" in the routing file. To run this command, the routing implementation must not use closures.
php artisan route:cache
command.Cause: Duplicate routes are defined in the routing file.
resource
method which is likely to result in duplication of its methods.3. [RuntimeException] Invalid filename provided.
php artisan optimize --force
naming.Cause: The corresponding file was not found when loading the class that needs to be compiled. The file path to be compiled is defined in the 5.2 version of
vendor/laravel/framework/src/Illuminate/Foundation/Console/Optimize/config.php
/vendor/laravel/framework /src/Illuminate/Database/Eloquent/ActiveRecords.php was not found, so this error was reported.
Modification plan: Temporarily comment out the
../ActiveRecords.php
4. InvalidArgumentException in FileViewFinder.php line 137: View [welcome] not found.
php artisan config:cache
, access the Laravel application on the browser The program welcome page reports this error.Reason: The Laravel application server is built on a virtual machine using Homestead. I ran this command outside the virtual machine, which caused the path in the generated config.php to be the local path, not the path on the virtual machine. So the view file cannot be found.
- app.debug=false
-
Cache configuration information php artisan config:cache -
Cache routing information php artisan router:cache Class map loading optimization
php artisan optimize
(including automatic loading optimizationcomposer dumpautoload
)As needed Only load necessary middleware
Use a just-in-time compiler (JIT), such as: HHVM, OPcache
2. Things to note when writing code
The specific implementation of routing is placed in the controller.
Do not define duplicate routes, pay special attention to the
resouce
method.Clear the role of each middleware and delete unnecessary middleware references.
0x06 Next step
The above tuning skills and coding considerations are mainly for the framework itself. There are many specific optimization skills in real business logic coding. This is not discussed.
Following optimization will focus on specific coding practices:
Use Memcached to store session config/session.php
-
Use a professional cache driver
Database request optimization
Write caching logic for the data set
-
Front-end resource merge Elixir
The above is the detailed content of Laravel framework performance tuning methods. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
