Home  >  Article  >  Web Front-end  >  Laravel framework performance tuning methods

Laravel framework performance tuning methods

一个新手
一个新手Original
2017-10-25 13:56:151995browse

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.

  1. Turn off application debug app.debug=false

  2. Cache configuration informationphp artisan config:cache

  3. Cache routing informationphp artisan router:cache

  4. ##Class map loading optimization

    php artisan optimize

  5. Automatic loading optimization

    composer dumpautoload

  6. Only load necessary middleware as needed

  7. Use a just-in-time compiler (JIT), such as: HHVM, OPcache

  8. Use PHP 7.x

Except In addition to the above optimization techniques, there are many coding practices that can improve Laravel application performance, which will not be explained in this article for the time being. (You can also follow my follow-up articles)

1. Close the application debug

Open the .env file in the application root directory and set debug to false.

APP_DEBUG=false

2. 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:clear

Run the above command to clear the cache of configuration information, that is, delete the

bootstrap/cache/config.php file

3. Cache routing information

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:clear

Running the above command will clear the routing cache, which means deleting the

bootstrap/cache/routes.php file.

4. Class map loading optimization

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.

You can add classes to be merged by modifying the

config/compile.php file.

In the production environment, there is no need to specify

--force The parameter file can also be automatically generated.

php artisan clear-compiled

Running 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 .

5. Automatic loading optimization

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 the

php artisan optimize --force command.

6. Load only necessary middleware as needed

The 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) in

app/Http/Kernel.php can greatly improve performance.

7. Using just-in-time compilers

HHVM and OPcache can easily improve the performance of your application by 50% or more without making any modifications. .

8. Using PHP 7.x

It can only be said that PHP 7.x has greatly improved performance compared to previous versions.

Well, limited to your real enterprise environment, this may not change for a long time, so I didn’t mention it.

0x02 Test Plan

We use a simple Apache ab command to test only the application entry file, and record and analyze the data.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  1. This environment runs on a Mac with 8G memory, 2.8GHz processor, and SSD hard drive.

  2. The test server is built using Homestead. The virtual machine is configured with a single-core CPU and 2G memory.

  3. The server PHP version is 7.1. If not specified, OPcache is turned on.

  4. The Laravel application tested was written in version 5.2. There are 85 routes defined in app\Http\routes.php.

  5. 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.

  • Runab -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 existbootstrap/cache/routes.php

  • No There are bootstrap/cache/compiled.php and bootstrap/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

1.2 Data Record

Laravel framework performance tuning methods

2. Close application debug

2.1 Operation

  • 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.2 Data record

Laravel framework performance tuning methods##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

Laravel framework performance tuning methods##3.3 Comparison results

Compare with the results of step 2 Found: After turning on the configuration information cache, the number of requests processed per second increased from 33-35 to 36-38, and the request response time dropped from about 290ms to about 260ms.

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 resultsLaravel framework performance tuning methodsCompare 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. Delete unnecessary middleware

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

    .

Laravel framework performance tuning methods

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

Laravel framework performance tuning methods

##5.3 Compare the result

with the result of step 4 and find: Delete After removing unnecessary middleware, the number of requests processed per second increased from about 60 to about 90, and the request response time dropped from 160ms to about 110ms.

The effect is very obvious. From the perspective of TPS, it has increased by 50%.

6. Turn on class map loading optimization

6.1 Operation

  • Based on step 5, run

    php artisan optimize - -force, confirm the generation of bootstrap/cache/compiled.php and 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.2 Data record

Laravel framework performance tuning methods##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

Laravel framework performance tuning methods##7.3 Comparison results

Compare with the results of step 6 Discovery: After turning off OPcache, the number of requests processed per second dropped from 110 to 15, and the request response time increased from below 100ms to above 650ms.

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.

0x04 Pitfalls

1. [LogicException] Unable to prepare route [/] for serialization. Uses Closure.

Running

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.

Modification plan: Put the specific implementation of routing into the controller.

2. [Exception] Serialization of 'Closure' is not allowed.

This error is reported when running the

php artisan route:cache

command.

Cause: Duplicate routes are defined in the routing file.

Modification plan: Check for duplicate routes in the routing file and modify them. Pay special attention to the

resource

method which is likely to result in duplication of its methods.

3. [RuntimeException] Invalid filename provided.

This error is reported when running

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

, but I don’t know why

/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

line in the above config.php.

4. InvalidArgumentException in FileViewFinder.php line 137: View [welcome] not found.

After running

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.

Modify the plan: ssh into the virtual machine and run this command.

0x05 Practical Skills

I have also stepped on the pitfalls and passed the test. Here is a brief summary of practical skills based on this experience.

1. Effective Laravel application optimization tips

Turn off application debug
    app.debug=false
  1. Cache configuration information
  2. php artisan config:cache
  3. Cache routing information
  4. php artisan router:cache
  5. Class map loading optimizationphp artisan optimize(including automatic loading optimizationcomposer dumpautoload)

  6. As needed Only load necessary middleware

  7. Use a just-in-time compiler (JIT), such as: HHVM, OPcache

2. Things to note when writing code

  1. The specific implementation of routing is placed in the controller.

  2. Do not define duplicate routes, pay special attention to the resouce method.

  3. 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:

  1. Use Memcached to store session config/session.php

  2. Use a professional cache driver

  3. Database request optimization

  4. Write caching logic for the data set

  5. Front-end resource merge Elixir

##0x07 Written at the end

I have seen many articles and debates on framework performance comparisons on the Internet, and I have also seen many simple posts of data . These are not enough to get a glimpse of the real situation, so we have this practice and made detailed records in the process. It provides readers with reference, comparison, and reflection during their practice. Readers who have questions about this practice are also welcome to submit questions and comments.


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!

Statement:
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