aungmyooo2k17

aungmyooo2k17

How to Optimize CPU Usage in Live View Application when introducing Scrolling Animation

I have a live view application that displays exchange rates data. Within the application, there is a box called “announcement” which shows scheduled or adhoc messages. Sometimes the message consists of around 3 lines, but occasionally it can be longer. However, the message box can only display up to 3 lines. So, when the message exceeds 3 lines, I decided to implement a scrolling animation behavior.

Here’s how I implemented it:

First, I added a Phoenix Hook to listen for when the message box is loaded. If the message box is loaded, I assume that there is a message to display.

Hooks.MessageBox = {
  mounted() {
    updateAnimationForMessage("message", this);
  },
  updated() {
    updateAnimationForMessage("message", this);
  },
};

Then, I added a JavaScript function to check the number of lines in the current message.

  const messageList = document.querySelector("#message-list");
  const content = messageList.querySelector("li:first-child");
  const cssCompute = window.getComputedStyle(content);
  context.pushEvent(event, {
    number_of_lines: Math.floor(
      parseInt(cssCompute.height) / parseInt(cssCompute.lineHeight)
    ),
  });
}

In the LiveView, I created a list with 10 rows of <li>Message here</li> elements using a for loop. These messages are scrolled up using CSS animation set to run infinitely. I push the number of lines count to the LiveView. The LiveView receives the number of lines and adds the CSS animation with inline styling.

["animation: message-slideup #{calculate_message_animation_time(number_of_lines) * 10}s linear infinite"]

I expected this code to work without any unexpected behavior or increased CPU usage. However, when I deployed it to production, I noticed that the CPU usage doubled with 200 clients accessing the application. Therefore, I am seeking help to resolve this issue.

Most Liked

thomas.fortes

thomas.fortes

What is the frequency of updateAnimationForMessage? If it’s running something like requestAnimationFrame and you’re pushing an event from there the event is hitting the server at least 60 times a second (more in high refresh rate monitors), which for 200 users would be 12000 events a second that the server has to handle, which would explain the memory use.

I agree with @ibarch, you probably should figure out a way to decouple the animation from the roundtrips to the server.

If it is only running a single time the problem isn’t in the javascript and we would need more info about your problem to figure out where the bottleneck is.

ibarch

ibarch

Try to apply phx-update="ignore" attribute to the parent container and fill it with dummy values on LW mount.
If the scrolling runs smoothly, then it’s likely that Morphdom patching is interfering with your manual DOM updates in the hook. To resolve this issue you can try to configure Morpdom to carry over some properties during patching:

const liveSocket = new LiveSocket("/live", Socket, {
  ...,
  dom: {
    onBeforeElUpdated(fromEl, toEl) {
      if (fromEl.matches(".parent")) {
        // I'm not sure which properties need to be moved from fromEl to toEl
      }
    }
  }
});

If animation jittering remains intact you need to debug your JS implementation.

Where Next?

Popular in Questions Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement