We are seeing significantly higher latency when calling System.cmd from an event in a LiveView vs when the LiveView first loads. In order to demonstrate this cleanly (our app is fairly complex) I created an entirely new 1.7.2 project with mix phx.new ptest --no-ecto
and added the following to lib/ptest_web/live/ls_live/index.ex
.
defmodule PtestWeb.LsLive.Index do
use PtestWeb, :live_view
def mount(_params, _session, socket) do
{:ok, assign(socket, :files, get_files())}
end
def render(assigns) do
~H"""
<button phx-click="refresh">refresh</button>
<div :for={file <- @files}><%= file %></div>
"""
end
def handle_event("refresh", _params, socket) do
{:noreply, assign(socket, :files, get_files())}
end
defp get_files() do
timer = Time.utc_now()
{files, _} = System.cmd("ls", [])
IO.puts("System.cmd took #{Time.diff(Time.utc_now(), timer, :milliseconds)} milliseconds")
String.split(files, "\n")
end
end
And, of course, the route: live "/ls", LsLive.Index, :index
.
That System.cmd
takes 2 milliseconds on average when called from mount
on page load vs 15.6 milliseconds on average when called from handle_event
when clicking the button. In our app we see about a 3x increase from ~11 millisecond when we call System.cmd from mount
to ~33 when called from handle_event
.
Any ideas why?