This is an after-the-fact summary. After going through a lot of pitfalls during the tuning process, we finally refined and implemented a preliminary performance test plan and summarized some practical tips for Laravel development from real test data.
0 x00 origin
Recently, a colleague reported that Laravel wrote an application that was a bit slow to respond, and ran the CPU full at 20 concurrent sessions. Even parts of the interface are written in NodeJS to solve the slow problem.
And my first reaction was how could a popular framework be so bad? There must be something wrong with the usage. To find out, I embarked on this Laravel application performance tuning tour.
0x01 Tuning Tips
The optimization techniques used in this performance test scenario are based on the Laravel framework itself and the tools it provides.
- Disabling Application Debug
app.debug=false
- Caching configuration Information
php artisan config:cache
- Caching Routing Information
php artisan router:cache
- Class map loading optimization
php artisan optimize
- Auto-loading optimization
composer dumpautoload
- Load only the necessary middleware as needed
- Use just-in-time compilers (JIT), such as HHVM and OPcache
- Use PHP to 7. X
In addition to the above optimization tips, there are a number of coding practices that can improve the performance of Laravel applications that are not covered in this article. (Also check out my follow-up posts.)
1. Disable application debug
Open the.env file in the application root directory and set debug to false.
APP_DEBUG=falseCopy the code
2. Cache configuration information
php artisan config:cacheCopy the code
Run the above command can combine the config folder all the configuration information to a bootstrap/cache/config. The PHP file, reduce the number of runtime files loaded.
php artisan config:clearCopy the code
Run the above command to clear cache configuration information, namely the bootstrap to delete/cache/config. PHP file
3. Cache routing information
php artisan route:cacheCopy the code
Run the above command will generate file bootstrap/cache/routes. The PHP. Route caching can effectively improve the registration efficiency of routers, especially in large applications.
php artisan route:clearCopy the code
Run the above command will remove the routing cache, that is, remove the bootstrap/cache/routes. The PHP file.
4. Class mapping loading optimization
php artisan optimize --forceCopy the code
Running the above commands can consolidate frequently loaded classes into a single file, increasing the efficiency by reducing file loading. This command will generate the bootstrap/cache/compiled PHP and bootstrap/cache/services. The json two files.
The classes to be merged can be added by modifying the config/compile.php file.
The –force parameter file can also be generated automatically in a production environment without specifying it.
php artisan clear-compiledCopy the code
Run the above command will remove class map load optimization, which is to delete the bootstrap/cache/compiled PHP and bootstrap/cache/services. The json two files.
5. Auto-load optimization
composer dumpautoload -oCopy the code
Laravel applications are built using Composer. This command converts the PSR-0 and PSR-4 into a class mapping table to speed up class loading.
Note: this is already done in the PHP artisan optimize –force command.
6. Only load the necessary middleware as needed
Laravel applications have a lot of middleware built in and enabled. Each Laravel request loads the associated middleware and generates all sorts of data. Commenting out unwanted middleware (such as session support) in app/Http/ kernel.php can greatly improve performance.
7. Use a just-in-time compiler
Both HHVM and OPcache can easily improve your application’s performance by 50% or more without making any changes.
8. Use PHP 7.x
Let’s just say THAT PHP 7.x is a huge performance improvement over previous versions.
Well, limited to your real business environment, this may not change for a long time, I didn’t say.
0x02 Test Scheme
We tested only the application entry files using the simple Apache ab command, and recorded and analyzed the data.
- Test only the application entry file index.php, and visit ‘/’ or ‘/index.php’ to return to the framework’s welcome page. More comprehensive performance testing requires testing for more interfaces to the application.
- Run the Apache ab command.
ab -t 10 -c 10 {url}
. This command makes 10 simultaneous requests to the URL and lasts for 10 seconds. Parameter Settings in this command vary according to the server performance to be tested. - In order to avoid data errors caused by machine fluctuations, the ab command is executed for each test condition for several times, and the command execution results are recorded. The number of requests processed per second and request response time are emphasized, and outliers are analyzed and eliminated.
- Each time you make changes to the test criteria, you need to access the welcome page in your browser to make sure that there are no access errors due to test criteria changes. If a page access error occurs, the test results will be incorrect.
Server Environment
All test data outside the context is meaningless and can only be compared under similar conditions.
- The environment runs on a Mac with 8 gigabytes of ram, a 2.8GHz processor, and an SSD drive.
- The test server was built using Homestead. The VM must have one CPU and 2 GB memory.
- If the server PHP version is 7.1, OPcache is enabled.
- The Laravel application tested was written in version 5.2.
app\Http\routes.php
There are 85 routes defined in. - During the test, except for the VIRTUAL machine, terminal and fixed browser window, the program running on the machine is not affected.
The above data, we can refer to in their own tests.
0x03 Test Process and Data
1. No optimization has been made
1.1 operating
- Perform the following operations according to the check items.
- run
ab -t 10 -c 10 http://myurl.com/index.php
Basic check item
- The env file
APP_DEBUG=true
- There is no
bootstrap/cache/config.php
- There is no
bootstrap/cache/routes.php
- There is no
bootstrap/cache/compiled.php
和bootstrap/cache/services.json
-
app/Http/Kernel.php
Enables most of the middleware in the - Browser access to the Laravel application welcome page ensures normal access
1.2 Data Records
2. Disable application debugging
2.1 operating
- Modify the. Env file based on Step 1
APP_DEBUG=false
. - Browser access to the Laravel application welcome page ensures normal access.
- run
ab -t 10 -c 10 http://myurl.com/index.php
.
2.2 Data Record
2.3 Comparison Results
Compared with the result of Step 1, after application Debug is disabled, the number of requests processed per second increases from 26-34 to 33-35, and the request response time drops from more than 300ms to about 290ms. The effect is not obvious, but it does improve to some degree.
Note: This section has a lot to do with the usage of logging in the application.
3. Enable caching configuration information
3.1 operating
- Run the following command based on Step 2
php artisan config:cache
, confirm generationbootstrap/cache/config.php
. - Browser access to the Laravel application welcome page ensures normal access.
- run
ab -t 10 -c 10 http://myurl.com/index.php
.
3.2 Data Record
3.3 Comparison Results
Compared with the result of Step 2, after configuration information caching is enabled, the number of requests processed per second increases from 33-35 to 36-38, and the request response time decreases from about 290ms to about 260ms. The effect is not obvious, but there is some improvement indeed.
4. Enable caching of routing information
4.1 operating
- Run the following command based on Step 3
php artisan route:cache
, confirm generationbootstrap/cache/routes.php
. - Browser access to the Laravel application welcome page ensures normal access.
- run
ab -t 10 -c 10 http://myurl.com/index.php
.
4.2 Data Records
4.3 Comparison Results
Compared with the result of Step 3, after the routing information caching is enabled, the number of requests processed per second increases from 36-38 to about 60, and the request response time decreases from 260ms to about 160ms. The effect is significant, and the TPS increases by 70%.
5. Delete unnecessary middleware
5.1 operating
- Based on Step 4, comment out unnecessary middleware code.
- Browser access to the Laravel application welcome page ensures normal access.
- run
ab -t 10 -c 10 http://myurl.com/index.php
.
Note: I commented out all middleware in this test. In practice, only the necessary middleware should be left.
5.2 Data Records
5.3 Comparison Results
Compared with the result of step 4, after the unnecessary middleware was deleted, the number of requests processed per second increased from about 60 to about 90, and the request response time decreased from 160ms to about 110ms. The effect was very obvious, and the TPS improved by 50%.
6. Enable class mapping optimization
6.1 operating
- Run the following command based on Step 5
php artisan optimize --force
, confirm generationbootstrap/cache/compiled.php
和bootstrap/cache/services.json
. - Browser access to the Laravel application welcome page ensures normal access.
- run
ab -t 10 -c 10 http://myurl.com/index.php
.
6.2 Data Record
6.3 Comparison Results
Compared with the result of Step 5, it is found that after the class mapping loading optimization, the number of requests processed per second increases from 90 to 110, and the request response time decreases from 110ms to less than 100ms, and the effect is quite obvious.
7. Close the OPcache
7.1 operating
- On the basis of Step 6, disable PHP OPcache and restart the server. Verify that OPcache is disabled via phpInfo () ‘s Zend OPcache.
- Browser access to the Laravel application welcome page ensures normal access.
- run
ab -t 10 -c 10 http://myurl.com/index.php
.
7.2 Data Records
7.3 Comparison Results
Compared with the result of step 6, after OPcache is disabled, the number of requests processed per second decreases from 110 to 15, and the request response time increases from less than 100ms to more than 650ms. When OPcache is turned on or off, the data is several times different.
After that, I re-enabled OPcache for PHP and the data was restored to step 6.
0x04 Trampled pit
1. [LogicException] Unable to prepare route [/] for serialization. Uses Closure.
This error is reported by running the PHP artisan route:cache command.
Cause: The closure is used to process “/” in the routing file. To run this command, the implementation of the route cannot use closures.
Modification scheme: Put the specific implementation of the route into the controller to achieve.
2. [Exception] Serialization of ‘Closure’ is not allowed.
This error is reported by running the PHP artisan route:cache command.
Cause: Duplicate routes are defined in the routing file.
Solution: Check the duplicate routes in the routing file and modify them. In particular, be aware that resource methods can lead to duplication of their methods.
3. [RuntimeException] Invalid filename provided.
This error is reported when running PHP artisan Optimize –force.
Cause: The file was not found when loading the class to be compiled. 5.2 version of the vendor/laravel/framework/SRC/Illuminate/Foundation/Console/Optimize/config. PHP defines the path to the file to compile, But I don’t know why/vendor/laravel/framework/SRC/Illuminate/Database/Eloquent/ActiveRecords. PHP is not found, so the error.
Fix: temporarily commented out the above config.php.. / ActiveRecords. PHP one line.
4. InvalidArgumentException in FileViewFinder.php line 137: View [welcome] not found.
After running PHP Artisan Config: Cache, the Laravel application on the browser welcomes this error.
Reason: The Laravel application server is built on a virtual machine through Homestead. I ran this command outside of the virtual machine, resulting in the generated path in config.php being the local path, not the virtual machine path. So you can’t find the view file.
Solution: Run the command on the VM using SSH.
0x04 Practical Skills
The pits were stomped, the tests were done. Here’s a quick summary of the practical tips for this experience.
1. Effective Laravel application optimization tips
- Disabling Application Debug
app.debug=false
- Caching configuration Information
php artisan config:cache
- Caching Routing Information
php artisan router:cache
- Class map loading optimization
php artisan optimize
(Includes auto-load optimizationscomposer dumpautoload
) - Load only the necessary middleware as needed
- Use just-in-time compilers (JIT), such as HHVM and OPcache
2. Precautions when writing code
- The implementation of the route is put into the controller.
- Do not define duplicate routes, especially
resouce
Methods. - Understand the role of each middleware and remove unnecessary middleware references.
0 x06 next
The above tuning tips and coding considerations are mainly for the framework itself. There are many specific tuning tips in real business logic coding that are not discussed here.
Subsequent optimization will focus on specific coding practices:
- Use Memcached to store session config/session.php
- Use a professional cache drive
- Database request optimization
- Write cache logic for data sets
- Front-end resources merged with Elixir
0x07 is written at the end
I’ve seen a lot of articles and debates about framework performance comparisons online, and I’ve seen a lot of simple postings of data. These are not enough to spy on the real situation, so we have this practice, and in the process of detailed records. In the practice of readers to provide reference, comparison, reflection. Readers who have questions about this practice are also welcome to submit questions and comments.
Without further ado, to learn more technical know-how, please follow the wechat public account: UP2048.
– EOF –
Recommended reading
- Laravel HTTP request, response, and form validation for Laravel mind mapping
- Laravel Mind mapping of Laravel HTTP routing, middleware, controller
- Laravel Mind mapping: Laravel core concepts
- A beginner’s guide to Laravel Mind Mapping