Resolución Práctica de Problemas de Rendimiento en Aplicaciones Web

Rate this content
Bookmark

En esta charla aprenderemos cómo resolver problemas de rendimiento. Aprenderemos cómo funciona el motor JS, veremos casos de uso en producción y obtendremos consejos prácticos que pueden ayudarte a mejorar el rendimiento de tu aplicación en un 90%.

Yonatan Kra
Yonatan Kra
8 min
15 Jun, 2021

Video Summary and Transcription

Esta charla discute el rendimiento en tiempo de ejecución en el desarrollo de software. Explora el concepto de recolección de basura y la importancia de optimizar funciones para una ejecución más rápida. El bucle de eventos y el perfilado también se destacan como herramientas esenciales para analizar y mejorar el rendimiento en tiempo de ejecución. Ejemplos de la vida real demuestran los beneficios del perfilado en la optimización de funciones y mejora del rendimiento de la aplicación. En general, la charla enfatiza la importancia de comprender y optimizar el rendimiento en tiempo de ejecución en el desarrollo de software.

Available in English

1. Introducción al rendimiento en tiempo de ejecución

Short description:

Hola, soy Jonathan, un arquitecto de software en Vonage. Hoy hablaremos sobre el rendimiento en tiempo de ejecución. La recolección de basura es el proceso en JavaScript donde se eliminan los objetos innecesarios de la memoria. Comparemos dos funciones, build Array y build Array2, para ver la diferencia en su rendimiento en tiempo de ejecución. Optimizar las funciones para una ejecución más rápida es crucial.

Hola, soy Jonathan, y soy un arquitecto de software en Vonage. También soy corredor. Esta soy yo ganando un medio maratón, y esto es relevante porque hoy hablaremos sobre el rendimiento en tiempo de ejecución. Así que aquí está la prueba de que puedes confiar en mí.

¿Qué es el rendimiento en tiempo de ejecución? Veamos un ejemplo, la recolección de basura. La recolección de basura es el proceso en JavaScript en el que JavaScript toma los objetos que ya no son necesarios y los elimina de la memoria. Eso es en una sola oración. ¿Cuál puede ser el problema con eso? Veámoslo.

Aquí tenemos dos arreglos, dos funciones. Uno es build Array, que crea un arreglo e itera n veces y agrega elementos a un arreglo. Este es build Array2. Preasigna el arreglo y luego itera n veces y coloca los mismos elementos en los mismos índices. Dos funciones que hacen cosas similares, pero veamos si difieren en algo. Aquí podemos ver el perfilado de estas dos funciones. build Array tardó más en ejecutarse que build Array2, y realmente podemos usar este perfil para ver por qué. Si profundizamos, podemos ver que en build Array, tuvimos alrededor de 1,250 recurrencias de recolección de basura menor. Si miramos build Array2, vemos que son alrededor de 200. Esta es una gran diferencia, y esto es en esencia el rendimiento en tiempo de ejecución, el perfilado y la optimización de funciones para que se ejecuten en menos tiempo. ¿Por qué es importante? Echemos un vistazo rápido al bucle de eventos.

2. Comprendiendo el Event Loop y el Perfilado

Short description:

El Event Loop es crucial para ejecutar el hilo principal de manera fluida tanto en el navegador como en Node.js. El perfilado de aplicaciones en el navegador nos permite analizar el rendimiento en tiempo de ejecución y optimizar tareas. Lo mismo se puede hacer en Node.js utilizando la página de inspección de Chrome. Ejemplos de la vida real demuestran cómo el perfilado ayudó a optimizar funciones y mejorar el rendimiento de la aplicación. En resumen, el perfilado es esencial para optimizar el rendimiento en tiempo de ejecución y hay muchos recursos disponibles para aprender más al respecto.

El Event Loop es lo que ejecuta nuestro hilo principal. Aquí es donde se ejecuta el código de nuestra aplicación. Si está bloqueado, entonces nuestro código no se está ejecutando, los otros códigos que necesitan ejecutarse, por ejemplo, en el lado del servidor en la respuesta de la API, o en el navegador, un usuario no puede hacer clic en nada, o las animations se quedarán atascadas.

Entonces esto es en el navegador, y esto es en Node.js. Y, nuevamente, lo importante que debemos entender aquí es que queremos que las tareas estén optimizadas lo máximo posible, y veamos cómo podemos ver las tareas y cómo podemos optimizarlas.

Esta es una función, algo bastante notable, debería resultarte familiar, en lugar de N tenemos un millón, crea un arreglo de un millón de elementos. Pero tenemos el set interval. Set interval es un temporizador, y un temporizador es una de las cosas que agrega tareas al Event Loop. Por lo tanto, podemos ver que cada segundo, algo bastante notable se agregará al Event Loop y se ejecutará como una tarea. Veámoslo en una demostración. Esta es nuestra función aquí. Se está ejecutando en el navegador, vamos a la pestaña de performance, y hacemos clic en grabar. Podemos grabar durante unos cinco segundos, por lo que deberíamos tener alrededor de cinco repeticiones de esta función. Y podemos ver estas elevaciones aquí. ¿De acuerdo? Podemos ver estas elevaciones aquí, y si nos fijamos un poco... Podemos verlo en el gráfico de llamas. Estas elevaciones ocurren cada segundo. Este es nuestro set interval. Y podemos ver que agrega una tarea cada vez, y la tarea es algo bastante notable. Por lo tanto, podemos ver todo lo que sucede durante el runtime y analizarlo para optimización. Tenemos una pestaña de resumen que nos muestra, por ejemplo, si observamos todo el runtime, muestra cuánto tiempo estuvo ocupada nuestra aplicación ejecutando scripts en comparación con el tiempo inactivo. O podemos ver el árbol de llamadas, por ejemplo. Veamos una tarea y veamos qué sucedió durante esta tarea, o podemos ver toda la grabación y buscar a lo largo de todas las llamadas algo bastante notable también, y aquí podemos ver algunas recolecciones de basura menores. Esto es lo esencial del perfilado de aplicaciones en el navegador. Veamos cómo puedes hacer esto en Node.js. En Node.js tienes la página de inspección de Chrome, y debes iniciar tu aplicación con la bandera --inspect. La aplicación se está ejecutando, y abres las DevTools dedicadas para Node, vas a la pestaña de perfilado, comienzas a perfilar, perfilar durante unos cinco segundos nuevamente, detienes el perfilado, y vemos nuestras elevaciones aquí nuevamente. Nuevamente, es lo mismo que en el navegador. Si sabes cómo optimizar en el navegador, puedes hacerlo en Node.js y viceversa. ¿Cómo puede ayudarte esto en la vida real? Veamos un ejemplo de la vida real. En una aplicación que construimos, usamos Seasium, que es un visualizador en 3D del globo, y tuvimos que colocar muchas entidades en este mapa, y esto hacía que la interfaz de usuario se bloqueara, por lo que hicimos un perfilado y descubrimos que dos funciones tardaban mucho tiempo en ejecutarse en cada fotograma. Estas son las actualizaciones de la etiqueta y el cartel, e investigamos estas funciones y descubrimos que si agregamos una bandera de actualización una vez sucia a las entidades, solo cuando las actualizamos, podemos optimizarlo para que las entidades que no se actualizaron no sean procesadas por estas funciones. Y los resultados son que del 50 por ciento del tiempo de ejecución de scripts, pasamos al dos por ciento del tiempo de ejecución de scripts y la aplicación se salvó y las personas pudieron interactuar con ella, por lo que el hilo principal no se bloqueó. En resumen, vimos el Event Loop y cómo administra nuestro hilo principal, por lo que no queremos bloquearlo. No puedo enfatizar lo suficiente la importancia del perfilado al optimizar el rendimiento en tiempo de ejecución, y realmente me gustaría que lo intentes, lo aprendas y lo disfrutes. Hay mucho para leer al respecto. Puedes leerlo en mi blog, puedes leerlo en el blog de Google Web Dev, y muchas cosas al respecto en Internet. Espero que lo hayas disfrutado, y gracias.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
Optimizing HTML5 Games: 10 Years of Learnings
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Optimizing HTML5 Games: 10 Years of Learnings
Top Content
The open source PlayCanvas game engine is built specifically for the browser, incorporating 10 years of learnings about optimization. In this talk, you will discover the secret sauce that enables PlayCanvas to generate games with lightning fast load times and rock solid frame rates.
When Optimizations Backfire
JSNation 2023JSNation 2023
26 min
When Optimizations Backfire
Top Content
Ever loaded a font from the Google Fonts CDN? Or added the loading=lazy attribute onto an image? These optimizations are recommended all over the web – but, sometimes, they make your app not faster but slower.
In this talk, Ivan will show when some common performance optimizations backfire – and what we need to do to avoid that.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Performance Debugging
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Maximize App Performance by Optimizing Web Fonts
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
Lazar Nikolov
Lazar Nikolov
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion
High-performance Next.js
React Summit 2022React Summit 2022
50 min
High-performance Next.js
Workshop
Michele Riva
Michele Riva
Next.js is a compelling framework that makes many tasks effortless by providing many out-of-the-box solutions. But as soon as our app needs to scale, it is essential to maintain high performance without compromising maintenance and server costs. In this workshop, we will see how to analyze Next.js performances, resources usage, how to scale it, and how to make the right decisions while writing the application architecture.