search
HomeWeb Front-endJS TutorialLaravel framework performance tuning methods

Laravel framework performance tuning methods

Oct 25, 2017 pm 01:56 PM
laravelmethodframe

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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

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.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

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 Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

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

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

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.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

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

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

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

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function