Performance of nested #if within #each


#1

Given the following template code:

{{#each post in posts}}
  {{post.title}}
  {{post.date}}
  {{#if session.user.isSuperUser}}
    <button {{action 'delete' post}}>Delete Post</button>
  {{else}}
    <button class="disabled" title="You don't have the rights to delete this post">Delete Post</button>
  {{/if}}
{{/each}}

I’m experiencing some performance issues with the rendering of the posts when the number of them is growing (it’s currently at around 200). Since session.user.isSuperUser isn’t changing for the whole duration of the rendering I thought of nesting the #each inside the #if which would give the following code:

{{#if session.user.isSuperUser}}
  {{#each post in posts}}
    {{post.title}}
    {{post.date}}
    <button {{action 'delete' post}}>Delete Post</button>
  {{/each}}
{{else}}
  {{#each post in posts}}
    {{post.title}}
    {{post.date}}
    <button class="disabled" title="You don't have the rights to delete this post">Delete Post</button>
  {{/each}}
{{/if}}

As far as I can tell, the rendering got faster with this tweak. The problem however is the duplicate code, which could be reduced by using a partial to display the post’s title and date, but that probably makes rendering slow again.

Any idea on solving both issues would be appreciated. Thanks!


#2

Each #if create’s a new “virtual view”, so that’ll be why it’s faster with the outer block. I’ve used this approach in certain places to get a speed improvement, and I personally think that that amount of duplication is just fine.

See this article for a deep dive into the view layer, I found it very useful.