Home Backend Development PHP Tutorial WordPress is a slow CMS

WordPress is a slow CMS

Sep 05, 2024 pm 04:31 PM

WordPress es un CMS lento

This post was initially published in 2014 in WordPress is a slow CMS - 2014

More than once I have found myself involved in the debate: is WordPress slow? Well, it's not so much of a debate when the only response from those attached to WordPress is that there are sites with many visits that have it and their performance is optimal. They themselves seem to forget that even the bubble sort algorithm behaves well for excessively large samples if it is "run" on a powerful computer. However, that does not mean that it is necessarily an efficient algorithm (in fact, it is not) if we look at its computational complexity. The same thing happens to WordPress. For the same amount of information, it will require much more powerful hosting than other CMS. Not only that, but as we will see, it is already a slow CMS whether or not it has a lot of information.

This does not mean that WordPress is bad. Nothing could be further from the truth. Just like in a car, speed is not everything. The same thing happens in the world of CMS. In fact, a large part of my web projects are with it. However, each project is different and, therefore, you have to know how to choose the best tools appropriately with your head and not with attachment.

As I am a technical person, my arguments will be based on technical aspects. Especially when I understand that WordPress is slow due to its design. I invite all those who disagree to leave me a comment with their reasoning.

Everything in one table.

When we are creating a database schema for a web project, the question arises whether to go for the practical or the efficient. In the case of WordPress, they opted for practicality and grouped posts, custom posts, resources and versions in the same table: wp_posts. This action has the advantage of simplifying the code and searches (although this is another thing that WordPress lacks as we will see in another post), but on the other hand it drastically reduces the efficiency of WordPress. Some examples to understand:

  • If we have 500 posts and each one has four different reviews (the current one and three more), it is as if we were dealing with 2,000 posts.

  • If we have 500 products with Woocommerce and each one has a featured image and four as a gallery of that product, it is as if our CMS had to work with 3,000 products.

  • If we have a small website with 35 pages and on it we have about 35 menu items, either with external or internal links. Our content manager would work as if we had 70 pages. Since each menu item counts as if it were an entry or a page in our CMS. In this example that is not much, but I put it so that you can see another of the influencing factors.

  • If you have 500 products and four languages, your WordPress is as if it worked on 2,000 products.

  • Now let's go to a real example as a summary: If you have a website with 500 products and for each of them you also have a featured image, four product gallery images and a pdf with technical information of each product. In addition, this site also has a blog with 200 entries each with their corresponding featured images. Also, if you have made the website with support for three languages ​​and establishing so that there are only two reviews per post. Every time WordPress launches a query against your database, it has to search among more than 5,500 elements. I despise others like menu items, pages and custom posts. Tips:

  • Limit the number of reviews to two or disable reviews completely:

1

2

3

4

//Limita las revisiones a dos:

define( 'WP\_POST\_REVISIONS', 2 );

//Desactiva totalmente las revisiones:

//define( 'WP\_POST\_REVISIONS', false );

Copy after login
  • Delete all revisions from time to time. You can do this by launching the following sql query:

1

2

3

4

DELETE a,b,c FROM wp_posts a

LEFT JOIN wp\_term\_relationships b ON (a.ID = b.object_id)

LEFT JOIN wp\_postmeta c ON (a.ID = c.post\_id)

WHERE a.post_type = 'revision'

Copy after login
  • Be austere with the images on your website. Also do not add images to your CMS that you are not going to use.

  • Avoid having a multitude of menus if they are not essential. Delete menu entries that you are not going to use.

  • If you have no other choice, because your client insists, than to use WordPress for medium or large projects, try to create auxiliary tables and thus lighten the load of wp_posts as much as possible

Your WordPress has Alzheimer's

WordPress seeks flexibility at any price, even at the cost of speed. Perhaps, because in the beginning it was only going to be a blog system and in that case so much flexibility could not cause so much damage. However, we started using it as a CMS and that's when the performance problems caused by flexibility began.

Déjame decirte una mala noticia: tu gestor de contenidos tiene alzheimer. Se le olvida todo de una petición a otra. Tendrás que repetirle en cada una de ellas los customs posts, los sidebars, o los menús que vas a usar. No te queda otra porque a él se le olvida. Es por ello, que si quieres añadir una entrada al menú del panel, por ejemplo, se lo tendrás que decir cada vez que se vaya a mostrar. Sí, da una enorme flexibilidad pero obliga a PHP y al CMS a procesar lo mismo una vez y otra vez, dando lugar a una perdida de eficiencia. Lo mismo le pasa a los plugins y es por ello que muchos plugins pueden ralentizar sobremanera tu sitio web. No por el sistema de plugins en sí ( que es magnifico como está pensado y programado ), sino por la obligación de los plugins de decir lo mismo una y otra vez y, por tanto, la necesidad de WordPress de recorrerlos completamente en cada petición.

Un CMS enfocado al rendimiento lo hubiera hecho de otra manera. Por ejemplo, haciendo que durante la activación del tema éste dijera que sidebars, custom posts o cualquier otro elemento necesita. WordPress lo registraría y se ajustaría adecuadamente de manera interna. Y lo mismo para los plugins. Pero, como digo anteriormente, un proceder así restaría mucha flexibilidad al CMS, algo que no les interesa.

Consejos:

  • Limita el número de plugins

  • Escoge temas minimalistas o que sólo tengan lo que necesites

  • Te recomendarán que uses un plugin de caché, yo no. Úsalo sólo en el caso que tu sitio web vaya extremadamente lento y siempre con pinzas. Hablaré de ello en otra entrada (edit: ya está disponible: No uses plugins de caché con WordPress , aunque básicamente es porque cortarás todo el funcionamiento interno de WordPress basado en hooks. Es decir, forzarás a trabajar a WordPress de una manera, que como hemos visto, no es la que han decidido para él.

Todo siempre a tu disposición

WordPress, como casi todo el mundo sabe, empezó como un sistema de blogs que se basaba en otro sistema anterior. No estaba pensado para proyectos grandes es por eso que su diseño tendió a lo simple. No clases, sólo funciones. Como cualquier aspecto de diseño, eso no tiene que ser algo necesariamente malo ( sino que se lo digan a los que usan escritorios realizados con GTK ), a no ser que busques la flexibilidad. Entonces, es cuando empiezan los dolores de cabeza.

Si vienes del mundo PHP, seguramente te sorprendas que con WordPress no has tenido ni que hacer requires, ni includes ni usar namespace. Es algo sencillo de entender, el motivo es que WordPress siempre carga todo su arsenal de librerías. Sí, siempre, las uses o no. Si lo sumamos a que tiene alzheimer, uff. Líneas de código que se tienen que leer si o si en cada petición. Un pasote. Pero, claro, piensa que es por la flexibilidad. Puedes usar una función del core sin tener que hacer un include a un fichero que puede que el día de mañana tenga otro nombre o esté en otro path.

A partir de PHP 5.6 hay soporte completo de namespace de funciones. Quizás esa sea una solución para WordPress. Pero en ese caso tendrán que tomar la difícil decisión de crear incompatibilidad hacia atrás. No sé lo que harán.

Nada puedes hacer para mejorar esto, ya que es parte del diseño de WordPress. Tan sólo te queda hacer tu parte, es decir, que tu código no siga esa línea. Si te decides a hacerlo, aquí mis consejos:

  • Crea funciones anónimas para los "actions" y que no sean más que un include a ficheros externos dónde tengas tu código. Así, si esa acción no llega nunca a lanzarse tampoco PHP tendrá que parsear todo el código. Ejemplo:

1

2

3

4

5

6

7

add\_action('admin\_init', function() {

    include(\_\_DIR\_\_."/zonas/panel/init.php");

});

 

add\_action('admin\_menu', function() {

    include(\_\_DIR\_\_."/zonas/panel/menu.php");

});

Copy after login
  • Para widgets, shortcodes y filtros, usa clases con namespace. Además, que estás clases se instancien mediante autocarga.

1

2

3

4

5

6

7

8

9

10

//Recomendable usar mejor: spl\_autoload\_register()

 

function __autoload($classname) {

    $file = str\_replace('', DIRECTORY\_SEPARATOR, $classname);

 

    include_once(BASE_PATH.$file.'.php');

}

 

add_shortcode( 'block', array('misshortcodesBlock', 'load') );

//...mis otros shortcodes, filtros y widgets, ....

Copy after login

Como resumen, hemos visto que WordPress tiene como principios de diseño a la simplicidad y flexibilidad, pero de una forma que le resta eficiencia. Hay que pensar que ninguna herramienta de desarrollo es buena para todo. Si alguien te lo presenta así es porque te está engañando o te vende una navaja suiza que no sirve para nada. WordPress cojea en su velocidad, pero para sitios webs escaparates es algo que no hay que darle mayor importancia. Para sitios en los que el negocio es la web se debería de plantear otras alternativas. Lo mismo para sitios con bastante tráfico. Si aún así queremos WordPress por su facilidad de uso y flexibilidad hemos de saber que habremos de compensarlo con un buen alojamiento, mucho cuidado con la selección de plugins y un tema de calidad y ajustado a nuestras necesidades.

The above is the detailed content of WordPress is a slow CMS. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles