作者都是各自领域经过审查的专家,并撰写他们有经验的主题. All of our content is peer reviewed and validated by Toptal experts in the same field.
Paul-Catalin Mestereaga
Verified Expert in Engineering
9 Years of Experience

Paul is a devoted Magento developer, a real go-getter, and a person who is truly passionate about the web.

Share

Magento performance is of paramount importance. Loading speed has a direct and measurable impact on the conversion rate of your website, 因此,有一个优化的Magento安装是至关重要的,你的Magento商店的成功,甚至可能是你的业务一般.

In this article I will present some ways in which Magento developers can optimize their Magento 2 installation, and explain how to do the following:

  • Check third-party modules and find bottlenecks
  • Enable full-page cache
  • Varnish, not files for full-page cache
  • Make sure full-page cache works, it can be broken so easily
  • Enable Production mode
  • CSS/JS minification
  • Enable Flat tables
  • Get the fastest hosting you can afford
  • Optimize images
  • Indexers to “Update on Schedule”
  • GZIP compression
  • Use Elasticsearch on catalog pages and search.
  • 检查页面加载后对服务器的不必要的Ajax回调(可能导致会话锁定)
  • Redis for page cache and session storage

Check Third-party Modules and Find Bottlenecks

There are many third-party Magento modules out there with bad code, using deprecated methods, or having compatibility issues with the latest stable version of Magento. The best way to identify heavy requests is to use a profiler. That helps you identify how many MySQL queries you have on a page and how many are identical. Knowing that, you can compact those queries into one, and thus speed up Magento.

初级开发人员在Magento中犯的主要错误之一是在循环中加载模型. Try to avoid that as much as you can. Load the whole collection with everything you need and then loop through it. 始终牢记时间和空间复杂性,并以优化的方式构建算法.

Magento performance chart

Look how your layout is loaded and which are the template blocks that perform the slowest, then look into that code. 查看Model CRUD指标,您可以在其中找到深刻的数据,例如将调用加载到循环中.

Magento Full-page Cache

When a user is accessing your store, a request is made to the server. 该请求由PHP处理,执行特定的操作和数据库查询,然后返回要显示给用户的相应HTML. Full-page cache stores that HTML response, 这样下一个相同的请求将直接返回它,跳过所有后端处理和数据库查询. This makes the website response much faster.

使用全页缓存作为您的Magento优化工作的一部分,可以极大地提高您的网站速度. 这将创建页面的缓存版本,并将它们交付给用户,而不是为每个请求运行所有查询. Of course, not all pages are cached. For example, the cart page will not be cached, otherwise, all users will see the first cached version of the page. These are dynamic pages or sections of pages that are user- and session-specific.

To enable Magento full-page cache you can run the following CLI command:

php bin/magento cache:enable full_page

To enable cache types you can run the CLI command:

php bin/magento cache:enable

You can also do it from Magento Admin by logging in as an administrator:

  1. Go To System > Tools > Cache Management
  2. Select the Cache Type you want to activate
  3. In the Actions dropdown select Enable and click Submit

Magento performance optimization screenshot

Use Varnish for Full-page Cache

When enabling full-page cache, use Varnish to handle it, not files. Magento strongly recommends using Varnish (or Redis) in production. 集成的全页缓存(对文件系统或数据库)比Varnish慢得多, and Varnish is designed to accelerate HTTP traffic.

You can find a full guide on how to install and configure Varnish in the official Magento 2 documentation.

To configure Magento to use Varnish log in to the Magento Admin as an administrator:

  1. Go to Stores > Configuration > Advanced > System > Full Page Cache
  2. From the Caching Application list, click Varnish Caching
  3. Enter a value in the TTL for public content field
  4. Expand Varnish Configuration and enter the specific information about your Varnish configuration

Magento performance optimization full-page cache screenshot

Make Sure Full-page Cache Works: It’s Easily Broken

Full-page cache can be easily broken in Magento 2. For example, If you want to exclude a block from the cache don’t use the attribute cacheable="false" in the XML layout when declaring your block. 这将禁用包含该块的整个页面的缓存,而不仅仅是该块. That is a mistake I’ve seen people make.

Look for the cacheable="false" 属性,并查看它们设置在哪些块上,以及在哪些页面上调用这些块. Thus, you can identify if trivial pages have problems with cache.

You can also test whether or not your page is cached manually. Put the store in Developer Mode on your local or stage environment:

  1. Clear Magento cache
  2. Load the page in the browser
  3. Inspect the page headers in your browsers debug network tab.
  4. Look for X-Magento-Cache-Debug: MISS
  5. Refresh the page, it should change to HIT

If it does not change to HIT it means the page is not cached and the cache is not working.

Don’t Forget to Enable Production Mode

Magento has three running modes, default, developer, and production mode.

The production mode is intended for deployment on a production system. This mode hides exceptions, 仅从缓存中提供静态文件,不允许您启用或禁用Magento管理中的缓存类型. It also prevents automatic code file compilation.

While working and developing the store, the developer mode is active. Don’t forget to switch to production mode when you deploy your site to the live server!

The CLI command to see the current mode is:

php bin/magento deploy:mode:show

The CLI command to switch to production mode is:

php bin/magento deploy:mode:set production

The CLI command to switch to developer mode is:

php bin/magento deploy:mode:set developer

You can find more detailed information about different Magento modes here.

CSS/JS Minification

Minifying the CSS and JS files is an important element of Magento 2 speed optimization. By minifying them we remove all the spaces, tabs, and newlines in the files. 生成的文件字符更少,因此尺寸更小,因此下载速度更快.

Magento has this feature built-in and you can enable CSS/JS minification in Admin. To enable JavaScript minification, follow these steps:

  1. put Magento on production mode
  2. Go to Stores > Configuration > Advanced > Developer
  3. Set Minify Javascript Files option to Yes
  4. Save Config
  5. Flush Cache at System > Cache Management page

Magento production mode screenshot

To enable CSS minification, the following steps are required:

  1. put Magento on production mode
  2. Go to Stores > Configuration > Advanced > Developer > CSS Settings
  3. Set Minify CSS Files option to Yes
  4. Save Config
  5. Flush Cache at System > Cache Management page

Magento CSS minification screenshot

Note: Do not merge JS files – just minify them.

Enable Flat Tables

Magento使用EAV(实体属性值)模型,该模型根据其值类型将实体的属性存储在多个表中. Using multiple tables, joins and requests on multiple tables are necessary to retrieve the data, which can slow down the queries.

Magento has the option to use flat tables for the catalog and products. Flat tables are created by merging all the attributes of an entity into one table. When requesting the data we need to query one table, making it much faster.

Magento generates and updates flat tables on every indexation. You can enable flat tables by logging into Magento Admin as an administrator:

  1. Go to Stores > Configuration > Catalog > Catalog > Storefront
  2. Select Yes for Use Flat Catalog Category
  3. Select Yes for Use Flat Catalog Product
  4. Save Config

Magento flat tables screenshot

Choose Fast Magento Hosting

Check out the Magento minimum requirements and see if your server meets them. You can see the official Magento 2.2.x technology stack requirements here.

The hosting configuration is very important for Magento 2 performance. There are also dedicated hosting services for Magento, though these can be more about marketing than anything else.

底线:获得你能负担得起的最快的托管解决方案,除非它对你的项目来说是多余的.

Magento Image Optimization

The size of your images obviously impacts the speed of your website. For example, if you have a catalog page with 20 products and each product image is 1Mb in size, that makes for a total of 20Mb to be downloaded when the page loads, and this could obviously be an issue in some scenarios (mobile devices, limited bandwidth in certain regions etc.).

检查你的图片是否进行了适当的优化,以及它们的质量和大小之间是否有一个良好的比例. Also, 确保您的图像没有通过CSS调整大小,而是将源文件调整为您需要的特定大小.

Another technique is to use lazy loading, which means loading your images after the page was fully loaded, or while the user scrolls through the catalog.

You can also use AWS or a CDN to deliver your content much faster. Let’s take a quick look at the differences between AWS, CDN and traditional hosting from a bitmap optimization perspective.

Traditional hosting

传统的方法是将图像等内容存储在与网站相同的服务器上. 这会占用磁盘空间和很大一部分带宽,从而产生大量的服务器负载. Obviously, scaling with traditional hosting can be an issue.

CDN (Content Delivery Network)

内容交付网络通常用于通过提供网站的部分内容来减少服务器的负载. Besides that, 它通过快速交付内容带来高性能,并通过使用多个网络调用带来高可用性.

AWS (Amazon CloudFront)

Amazon CloudFront是一个高度安全的内容分发网络(CDN),提供网络和应用程序级别的保护. Check this tutorial on how to get started with AWS and deliver content faster.

In addition, you can use AWS to resize images on the fly based on dimensions passed via a query parameter. For additional information, consult this tutorial on Resizing Images with Amazon CloudFront and Lambda@Edge.

Set Indexers to “Update on Schedule”

Magento indexers can be set to two modes: “Update on Save” or “Update on Schedule.”

When they are set to “Update on Save” every time you save a product, attribute or a category, the specific index starts running. Indexers can become resource consuming and that might slow down your server.

The best mode to set the indexers is to “Update on Schedule”. 通过这种方式,您可以确保它们在您设置的特定时间由cron作业执行. Choose a time when the traffic on your website is low.

You can view the current indexers mode by running the command:

php bin/magento indexer:show-mode

Or in Magento Admin by going to:

System > Index Management

You can change the indexers mode to “Update on Schedule” by running the command:

php bin/magento indexer:set-mode schedule

You can change the indexers mode to “Update on Save” by running the command:

php bin/magento indexer:set-mode realtime

And here it is in Magento Admin:

System > Index Management: Select all indexers and from Actions dropdown select “Update on Schedule”

image alt text

You also configure the Scheduled Tasks by going into Admin to:

Store > Settings > Configuration > Advanced > System > Cron (Scheduled Tasks)

Expand “Cron configuration options for group: index”

Magento cron configuration dialog

GZIP Compression

Gzip is a method of compressing files for faster network transfers. 压缩允许您的web服务器提供更小的文件大小,为您的网站用户提供更快的加载速度. However, this comes at a cost.

While compressing a file you load the CPU, and the more you compress a file the longer the process it takes. Even though this can increase the server CPU load, it could also substantially decrease bandwidth usage. With gzip, you can choose between different levels of compression, ranging from 1 to 9.

On level 1 you have the fastest compression time, but a lower compression ratio. On the opposite side, on level 9 you have the highest compression rate but a lower speed. The default configuration of gzip uses level 6, favoring compression over speed. Nginx though uses level 1, favoring speed over file size.

To turn on gzip compression and activate the mod_deflate module of Apache, you can add this by updating your .htaccess file and uncomment the appropriate lines as shown below. The mod_deflate 模块在将静态资源传输到浏览器之前将其压缩成较小的文件.



############################################

## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json image/svg+xml

    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary


另一种提高网站速度的方法是使用Elasticsearch来搜索目录页面和搜索结果. Setup your Elasticsearch server and connect your Magento store to it. Searching becomes much faster by using Elasticsearch.

This official guide explains how you can configure Magento with Elasticsearch.

To configure Magento to use Elasticsearch log in to the Magento Admin as an administrator:

  1. Click Stores > Settings > Configuration > Catalog > Catalog > Catalog Search.
  2. From the Search Engine list, click Elasticsearch or Elasticsearch 5.0+ as the following figure shows. (The Elasticsearch 5.0+ option is not available for Magento 2.1.)

Setting up Elasticsearch in Magento

Check for Unnecessary Ajax Calls

Calls back to the server after page load can cause session locks. 一种方法来检查所有的Ajax调用,你的页面正在做的是通过使用DevTools在Chrome. You can open it by right click on the page and selecting Inspect.

Go to the network tab and there you can filter the request by XHR. 现在,您可以看到页面的所有Ajax请求,并对它们进行检查,以确定哪些请求在特定页面上是必需的.

Ajax Calls in Magento

Redis for page cache and session storage

Redis is an optional back-end cache solution to replace Zend_Cache_Backend_File, which is used in Magento 2 by default.

Why Use Redis?

Using Redis can have multiple advantages:

  • You can replace memcached with Redis because it can be used also for PHP session storage.
  • Redis supports on-disk save and master/slave replication, which is a highly requested feature that is not supported by memcached. Replication avoids a single point of failure and provides high availability.
  • 标签操作不需要完全扫描每个缓存文件,因为Redis是通过索引文件中的标签来工作的.
  • The back-end supports tag-based cache cleanup without foreach loops.

There is also a main downside:

  • Because Redis is an in-memory store, all your data must fit in memory, meaning it’s only limited by RAM speed and capacity.

Configure Magento to use Redis for session storage

Following is a sample configuration to add to app/etc/env.php:

'session' =>
array (
  'save' => 'redis',
  'redis' =>
  array (
    'host' => '127.0.0.1',
    'port' => '6379',
    'password' => '',
    'timeout' => '2.5',
    'persistent_identifier' => '',
    'database' => '2',
    'compression_threshold' => '2048',
    'compression_library' => 'gzip',
    'log_level' => '1',
    'max_concurrency' => '6',
    'break_after_frontend' => '5',
    'break_after_adminhtml' => '30',
    'first_lifetime' => '600',
    'bot_first_lifetime' => '60',
    'bot_lifetime' => '7200',
    'disable_locking' => '0',
    'min_lifetime' => '60',
    'max_lifetime' => '2592000'
  )
),

You can check here all the details about the parameters, 以及如何做一个基本的验证,你的Redis安装与你的Magento一起工作良好.

Configure Magento to Use Redis for Page and Default Cache

There are two ways to configure Redis for page and default cache. You can manually edit app/etc/env.php file or you can use the command line, which is the recommended method because also provides validation.

For the default cache run the command:

php bin/magento setup:config:set --cache-backend=redis --cache-backend-redis-=...

Specify parameters that are specific to Redis default caching.

For the page cache run the command:

Php bin/magento setup:config:set --page-cache=redis --page-cache-redis-server=redis.example.com --page-cache-redis-db=1

This command enables Redis page caching, sets the host to redis.example.com and assigns the database number to 1. You can check all the details on the Magento DevDocs.

Magento Performance Optimization Summarized

We’ve covered quite a few approaches to Magento 2 performance optimization, so let’s do a quick recap.

Identifying and solving bottlenecks will make a huge difference in processing your data. 使用全页缓存和清漆也会提高你的网站速度和加速HTTP流量. You should always use Magento on production mode on your live server, no excuses. Use minification to decrease the size of CSS and JS files, a smaller file will both download faster and use up less bandwidth.

Enable flat tables to decrease the database requests and improve database response time. Optimize your images and use a CDN if possible. Set indexers to update on schedule and enable the Magento cron. Enabling gzip compression will also decrease the size of the files to be downloaded. 使用Elasticsearch将提高目录页面的速度,搜索结果页面将加载得更快. 使用Redis进行页面缓存和会话存储,这比默认的memcache要快得多.

You can implement all of these recommendations or just a few that you have not used so far. Even a couple should be enough to improve Magento performance, which should hopefully transform into more conversions.

Understanding the basics

  • What is Magento?

    Magento是一个建立在开源技术之上的现代电子商务平台,它超越了购物车系统, offering powerful tools for B2C, B2B, and B2B2C.

  • What language is Magento written in?

    Magento is written in PHP.

  • What is Magento Cloud?

    Magento Commerce Cloud是专门为云基础设施创建的Magento托管和自动化托管平台. This version combines Magento Commerce and cloud infrastructure hosting, with a few differences and added features.

  • Why use Magento 2?

    Magento 2 is designed for growth and built for flexibility. It can deliver a seamless shopping experience, reduce business costs, automate repetitive tasks and save hours of manual effort. Also by being agile and user-friendly, with Magento you can go to market quickly.

  • How to speed up Magento 2?

    Use full-page cache, Varnish, and enable flat tables. Use minification for CSS and JS files. Optimize images and use a CDN if possible. Set indexers to update on schedule. Enable Magento cron and gzip compression. Use Elasticsearch for catalog and search. Use Redis for page cache and session storage.

  • Is Magento 2 free?

    Magento 2 is offered in both free or paid versions. The offered solutions are Magento Open Source and Magento Commerce. Magento Open Source is free for everyone. Magento Commerce it is a paid solution that can be also hosted in Magento’s own cloud, Magento Commerce Cloud.

Hire a Toptal expert on this topic.
Hire Now
Paul-Catalin Mestereaga

Paul-Catalin Mestereaga

Verified Expert in Engineering
9 Years of Experience

Timișoara, Timiș County, Romania

Member since March 29, 2017

About the author

Paul is a devoted Magento developer, a real go-getter, and a person who is truly passionate about the web.

作者都是各自领域经过审查的专家,并撰写他们有经验的主题. All of our content is peer reviewed and validated by Toptal experts in the same field.

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

Toptal Developers

Join the Toptal® community.