Anything wrong with hardcoded lists in liveview templates?

Simple question, I’m implementing a pattern like this:

<a
  :for={
    {url, icon, name} <- [
       ....multiple hard coded values here
    ]
  }
  href={url}
  class="text-gray-400 transition hover:text-white"
>
  <span class="sr-only">{name}</span>
  <.icon name={icon} class="h-6 w-6" />
</a>
>

Any reason not to do this? I could assign it to assigns as well on top of the component for example, but I’m not sure that makes a difference.

2 Likes

I believe LV only sends dirty parts of the tree, so I don’t think it would matter if you used an assign here or not. The literal should be fine.

However, I suspect you would get a performance boost by unrolling the loop into its constituent <a> elements because then the whole thing would be treated as static text and ignored. There might be some cases where the :for is actually more efficient, though, because it can re-use its own static and send less over the wire.

If you’re optimizing it’s best to look at the diffs and see what gets sent over.

1 Like

Yes, you can do that. I have a couple of places where I do it too.

To expand on what @garrison said – there’s two axis to LV optimizations:

Static vs. dynamic content. Static content is only sent once on the first time a component is rendered (the :static part of the rendered struct returned by the ~H sigil). So you want to optimize for more static content, where it’s not repeated.

And then there’s minimising diffs or even the need to send anything in the first place. That’s where the same component (same fingerprint) compares the past and current assigns and where they differ the dynamic parts updates are sent to the client. So you want to minimize the dynamic parts changing at all as well as having the dynamic parts be as small as possible if they need to change.

Therefore here you could hardcode the list elements and maybe get more things static, but it’s likely better to benefit from the reuse of the static portions of the iterated list. Given neither your assign nor the hardcoded list will ever change that’s not a factor.

3 Likes

I would expect gzip (or zstd, do we have that yet?) to reduce the size of the unrolled version proportionately, so that option is more attractive than it appears. I would think avoiding the codepaths that run the for loop or compare fingerprints would be a performance improvement, and the gzip is going to be very fast native code that runs anyway so has little marginal cost.

But back in reality this doesn’t matter at all, just do whatever’s more readable unless this happens to be an extremely performance-critical codepath, in which case, benchmark.