4

In my views, I am rendering a partial. This is actually a row element that shows up in a table some 500 - 600 times. I have eager loaded all associations. But, the issue is, same partial takes abruptly different render-time some times.

My rails server o/p:

Rendered admin/invoices/_update.html.erb (1330.3ms)
Rendered admin/invoices/_update.html.erb (4.8ms)
Rendered admin/invoices/_update.html.erb (4.8ms)
Rendered admin/invoices/_update.html.erb (8.8ms)
Rendered admin/invoices/_update.html.erb (4.4ms)
Rendered admin/invoices/_update.html.erb (1309.9ms)
Rendered admin/invoices/_update.html.erb (4.7ms)
Rendered admin/invoices/_update.html.erb (4.6ms)
Rendered admin/invoices/_update.html.erb (4.6ms)
Rendered admin/invoices/_update.html.erb (1322.6ms)
Rendered admin/invoices/_update.html.erb (4.2ms)

Also, there is no particular row that takes longer every time.

In my view file:

<% @updates.each do |update| %>
<%= render :partial => 'update', :locals => {:user => update[0]} #each of this is  a row %>
<% end %>

UPDATE: Also suggest if this a good way to do this? i.e: looping over a partial so many times. I can't use pagination and Ajax to fasten up things.! Any other approach.?

Nerve
  • 6,463
  • 4
  • 29
  • 29

2 Answers2

6

Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:

<%= render :partial => 'update', :collection => @updates %>

There is also a shorthand for this. Assuming @updates is a collection of update instances, you can simply write this in the index.html.erb to produce the same result:

<%= render @updates %>

Section 3.4.5 of the Rails Guides explains this in detail.

Syed Aslam
  • 8,707
  • 5
  • 40
  • 54
4

Though I'm not sure why the lag spikes in the rendering, i strongly recomend inverting the order: You give all the updates to the partial and inside it you iterate and render the rows.

In view file

    <%= render :partial => 'update', :locals => {:updates => @updates} %>

And inside the update partial

    <% updates.each do |update| %>
       RENDER LOGIC
    <% end %>

This why you don't suffer the partial loading overhead for every row in your update. Hope this helps!

  • Hey, thanks for this. I tried this, and the render is instantly down by roughly 15% - 20%. However still couldn't understand the reason for those irregular spikes. – Nerve Jan 11 '13 at 18:59
  • Are your results from a development enviroment? Keep in mind that in production, views code is cached, so maybe the other suggestion could make more sense performance-wise. Try making your benchmark in a production enviroment, as those are the rendering times that will matter in the end. – CristianDonosoC Jan 11 '13 at 19:31
  • Enabled asset pipelining, precompiled the assets and whoa, the page shoot up right there! lightening fast! Thanks. – Nerve Jan 11 '13 at 19:56