Performance: Why views present data
This concept affects how quickly the page content appears and updates by controlling how data is rendered in the browser.
<%= render partial: 'item', collection: @items %>
<!-- _item.html.erb -->
<div>
<strong><%= item.name %></strong>
<p><%= item.description %></p>
</div><% @items.each do |item| %> <div><%= item.name %></div> <div><%= item.description %></div> <% end %>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Loop with inline ERB | Many nodes (2 per item) | N reflows (N = items) | High paint cost | [X] Bad |
| Partial with collection rendering | Fewer nodes, grouped | Single reflow | Lower paint cost | [OK] Good |
@items = ['apple', 'banana', 'cherry'], what will this view code output?<ul>
<% @items.each do |item| %>
<li><%= item.upcase %></li>
<% end %>
</ul><ul>
<% @products.each do |product| %>
<li><%= product.name %></li>
<% end %>
</ul><ul>
<% @users.each do |user| %>
<li>
<%= user.name %>
<% if user.email.present? %>
(<%= user.email %>)
<% end %>
</li>
<% end %>
</ul>Pass the test and this pattern moves unknown