Home PHP Framework Laravel Recommended 18 essential tips for Laravel performance optimization

Recommended 18 essential tips for Laravel performance optimization

Aug 11, 2022 am 09:55 AM
laravel

Laravel is a popular open source PHP framework known for its strong security and simple yet complex coding architecture. It's a great choice for building cutting-edge web applications that drive revenue and grow your business.

Today, there is no PHP developer who is not influenced by Laravel. They are either junior or mid-level developers who like the rapid development that Laravel offers, or they are senior developers who are forced to learn Laravel due to market pressure.

With over 1 million websites powered by Laravel, Google has pushed the importance of website speed, and users are increasingly unwilling to accept anything other than an incredibly smooth user experience. Some People are giving frameworks like PHP and Laravel a reputation for not performing as well as other frameworks. While this may well be true, it doesn't mean there's nothing you can do about it. So, in this guide, we’ll take a deep dive into how to optimize Laravel’s performance.

Currently, Laravel has become a very popular framework for developing business and e-commerce applications. Most organizations prefer to use Laravel to build their business applications. there are many reasons. But today we are only focusing on performance optimization.

Why is Laravel's performance optimization so important?

This article will introduce several important techniques and guide you in each step to optimize your Laravel website. While some of the steps may sound technical, they are easy to follow and recreate on your own screen.

1. Route caching

Laravel allows caching of routes. You can execute the Artisan command:

php artisan route:cache
Copy after login

All routes will be cached in the routes.php file.

The next time routing is needed, the cache will be accessed instead of the routing file. This can improve site performance by routing requests quickly.

To clear the cache, you can use a command similar to:

php artisan route:clear
Copy after login

Route caching is a simple way to make your website smoother and load faster.

2. Use Artisan commands effectively

One of the best features of Laravel is its command line tool Artisan. If used effectively, it can improve the performance of your application.

You can cache routes and configurations. You can execute the following command to cache configuration and routes:

php artisan config:cache

php artisan route:cache
Copy after login

Note: Artisan Optimize was removed in Laravel 5.5, it worked in previous versions.

php artisan optimize --force
Copy after login

Be sure to clear the cache when adding new configurations or new routes. The cache can be cleared effectively using the command below.

php artisan config:clear
php artisan route:cache
php artisan view:clear
Copy after login

3. Configure cache

Laravel provides a very interesting command: Artisan Cache Config, which Very helpful for improving performance. The basic usage of the command is:

php artisan config:cache
Copy after login

After the configuration is cached, it will not have any impact on the changes you make. If you want to refresh the configuration, just run the above command again. If you need to clear the configuration cache, use the following command:

php artisan config:clear
Copy after login

4. Get data directly

When you execute any query in Laravel , Laravel executes the query lazily (lazy loading), it only fetches the data when needed.

In some cases, this lazy loading behavior can increase the number of queries executed while reducing application performance.

Let's look at a simple example to understand this behavior in detail. If you want to get the author names of books in the library.

With lazy loading, you will end up executing N 1 queries to find the results. You can see it in the code example below.

$books = Book::all();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

In the code below, the query is executed every time the for loop is executed. To solve this problem, Laravel allows you to load data directly.

This will increase your query execution time and reduce the number of queries. The code example below shows how we can easily load a complete list in one query.

$books = Book::with('author')->get();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

Let’s look at a simple example to understand this behavior in detail.
If you want to get the author's name of the books in the library.

If you don't use eager loading, you will end up executing N 1 queries to find the results.
You can see it in the code example below.

$books = Book::all();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

In the code below, each time the for loop is executed, a query is executed.
To solve this problem, Laravel allows preloading related data.

这会增加的查询执行时间并减少查询次数。
下面的代码示例展示了我们如何在一个查询中轻松加载完整列表。

$books = Book::with('author')->get();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

5.  Composer 优化

Laravel 使用一个名为 Composer 的包管理工具来管理不同的依赖项。 当你最初安装 Composer 时,默认情况下它会将开发依赖项加载到你的系统中。

这些依赖项对于开发网站很有用。 但是,一旦你的网站完全投入运营,就不再需要它们,事实上,它们只会减慢速度。

当使用 Composer 安装包时,使用 --no-dev-o 参数来移除 dev 依赖:

composer install --prefer-dist --no-dev -o
Copy after login
Copy after login

此命令允许 Composer 创建用于优化自动加载器和提高性能的目录。 它只是请求获取和打包官方发行版,没有开发依赖项。

注意不要消除任何运行时依赖项。 这可能会危及网站的性能,甚至导致其崩溃。

6. 压缩绑定配置

Laravel mix 可以在这里为你提供帮助,它编译所有 CSS 并提供单个 app.css 文件,从而将多个 HTTP 请求减少为单个。 你还可以使用 laravel-mix-purgecss 包从项目中删除未使用的 CSS,只需将其安装在你的开发项目中:

npm install laravel-mix-purgecss --save-dev

# or

yarn add laravel-mix-purgecss --dev
Copy after login

在你的文件 webpack.mix.js

const mix = require('laravel-mix');
require('laravel-mix-purgecss');
mix.js('resources/js/app.js', 'public/js').sass('resources/sass/app.scss', 'public/css').purgeCss();
Copy after login

7. 队列

Laravel 队列就像你的 CPU 一样工作。 每当你的计算机处理一项任务时,它都会以最有效的方式执行,而不会降低用户体验的质量。 这意味着当你渲染文件或执行资源密集型操作时,你的 CPU 会确保你仍有剩余的处理能力用于其他任务,直到达到其限制。

例如,当用户注册到网站时,我们必须在后端执行许多操作,例如存储用户信息、发送激活邮件、发送欢迎邮件等。如果我们只是发送一封邮件(没有队列),那么它会大约需要 4-5 秒。并且用户必须等到请求。因此,对于队列,我们只需要在执行所需的验证并显示用户成功消息后将操作推送到队列中。之后,我们只需要在队列执行时处理基本的事务。

简单的例子是:

  • 发送电子邮件
  • 下载文件
  • 上传文件

这些任务不需要用户看到,可以作为后台进程完成。

Laravel 还有几个队列驱动程序支持文档,并为每个文档提供独特的解决方案,例如 Horizon,一个监控队列系统的仪表板。

8. 快速缓存或会话驱动程序

为了提高 Laravel 应用程序的性能,我们可以存储会话并将它们缓存在 RAM 中。 Memcached 是最好和最快的缓存和会话驱动程序。 Laravel 可以灵活地将一个缓存/会话驱动器切换到另一个。

对于会话驱动,我们可以在 config/session.php 中更改驱动键,对于缓存,我们可以在 config/cache.php 文件中更改驱动键。

9. 数据库索引

当我们谈论提高应用程序的性能时,我们会遵循 Laravel 中的许多实践,例如缓存、数据加载、资产缩小等。但是还有一件事可以帮助我们提高性能,即数据库索引。 这基本上是一种数据库级技术。

在技术实现的角度看,数据库索引是基于数据库表的一个或多个列的数据结构。索引背后的主要思想是加快数据检索。它有助于轻松定位数据,而无需在每次访问数据库时遍历每一行。

使用列,索引有助于最小化处理的每个查询的磁盘访问。使数据库索引成为一种强大的数据库优化技术还可以提高数据库的整体性能。

在 Laravel 中,我们可以使用迁移来创建索引。下面是示例:

Schema::create(‘users’, function (Blueprint $table) {
   $table->string(’email’)->index();
   });
Copy after login

10. 利用 JIT 编译器

PHP 是一种计算机机器和服务器端语言。它本身不理解 PHP 代码。通常,程序员使用编译器将代码编译成字节码并解释 PHP 代码。程序编译过程会影响 Laravel 应用程序的性能和用户体验。所以,Laravel 程序员可以使用 Zend Engine 自带的即时编译器来快速编译代码。

11. 压缩图像

如果你的项目中包含许多图像,你应该压缩所有图像以优化性能。
有一些方法可以进行优化。
但是不同的图像需要不同的工具来保持图像的质量和分辨率。

如果你使用 Laravel Mix,建议在编译图像时使用像 ImageMin 这样的 NPM 包。
对于非常大的图片,先试试 TinyPNG 压缩图片,然后再用 ImageMin 尽量压缩。

12. 视图缓存

另一个方面是视图缓存。
视图缓存存储编译后的的 Blade 模板以提高项目的速度。
你可以使用下面的 artisan 命令手动编译所有视图并优化性能:

php artisan view:cache
Copy after login

上传新代码时记得清除缓存;否则,Laravel 将使用你的旧视图,你将花费大量时间尝试解决此问题。运行以下命令清除视图缓存:

php artisan view:clear
Copy after login

13. 删除未使用的服务

你可以使用 Laravel 提供的服务容器框架轻松地注入服务。你只需在 config/app.php 文件中的 providers[] 数组中添加服务的名称。

但同时,你应该只打开你正在使用的那些服务。应停止所有其他未使用的服务。

你可以通过在 config/app.php 文件中注释掉这些服务来停止这些服务。这将减少你的应用程序启动所需的时间并提高其性能

14. 使用 CDN 加载静态内容

CDN 是在全球范围内加载静态内容的好方法。如果你的应用程序越来越流行,你可能需要为你的应用程序使用 CDN 服务

让我举一个简单的例子,你在美国的服务器上托管了你的应用程序。现在,如果你有来自印度的请求,你需要很长时间才能为该请求提供内容。

为了解决这个问题,CDN 应运而生。 CDN 可以帮你缓存多个静态页面。现在你的请求将首先到达 CDN,如果内容存在于 CDN 中,则直接提供页面。这极大地提高了你的内容服务速度以及最终用户体验。

15. 压缩 CSS 和 JS

在生产环境中实际捆绑这些文件之前,你应该始终压缩 CSS 和 JavaScript 文件。 这将增强你的用户体验并减少 HTTP 调用。 这是一个很棒的 Laravel 性能优化技巧。

有多种工具可用于压缩这些文件并将它们捆绑为单个文件。 你可以使用 Laravel-packer,它允许你打包和压缩你的 CSS 和 JavaScript 代码。 如果需要,你还可以调整图像大小以生成缩略图。

16. 移除开发依赖

首次安装 Laravel 或 composer 时,通常会默认将开发依赖项注入到你的系统中。 虽然这些依赖项确实有助于构建你的网站,但当你的网站启动并运行时,你不需要这些依赖项。

你可以通过 Artisan 输入这个简单的命令来删除这些依赖项:

composer install --prefer-dist --no-dev -o
Copy after login
Copy after login

注意: 开发依赖项不同于运行时所需的依赖项。 不要删除运行时依赖项,因为这可能会影响你网站的性能,甚至会导致你网站的某些部分崩溃。

17. 将Lumen用于小型项目

有时开发小型应用程序(例如移动或 Angular 应用程序)不需要使用像 Laravel 这样的全栈框架。 在这种情况下,请考虑改用 Lumen。

Lumen 是由 Laravel 的同一创建者开发的微框架。 就像 Laravel 的轻量级版本一样,Lumen 是关于微服务的速度和性能的。 在构建 Web 应用程序时,它需要最少的设置和替代路由参数,从而加快开发过程。

例如,Lumen 每秒可以处理 100 个请求。 你还可以集成来自第三方的工具或软件包以获得新功能。 此外,Lumen 支持所有平台并允许你升级到 Laravel。

18. 限制包含的库

Laravel 让你可以自由添加任意数量的库。 虽然这是一个很棒的功能,但添加大量库会给应用程序的性能带来很大压力。 它还会影响整个用户体验。

因此,扫描代码中当前使用的所有库数据至关重要。 你可以在 config/app.php 文件中找到这些库。 在检查库时,删除你知道对你不再有用的库。

查看 composer.json 中不需要的依赖项也是一个好办法。

感谢你们的阅读!

原文地址:https://devdojo.com/techvblogs/how-to-optimize-laravel-for-performance

译文地址:https://learnku.com/laravel/t/69775

The above is the detailed content of Recommended 18 essential tips for Laravel performance optimization. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Questions and Answers on PHP Enterprise Application Microservice Architecture Design Questions and Answers on PHP Enterprise Application Microservice Architecture Design May 07, 2024 am 09:36 AM

Microservice architecture uses PHP frameworks (such as Symfony and Laravel) to implement microservices and follows RESTful principles and standard data formats to design APIs. Microservices communicate via message queues, HTTP requests, or gRPC, and use tools such as Prometheus and ELKStack for monitoring and troubleshooting.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Which is the better template engine, Laravel or CodeIgniter? Which is the better template engine, Laravel or CodeIgniter? Jun 03, 2024 am 11:30 AM

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

See all articles