5

I am new to rails and I am trying to render a partial within a loop as such.

Here , books is an array eager loaded in controller.

 books.each do |book|
   <%= render 'books/book', :book => book %>
 end

This works fine. But when the books array is really huge, it takes time for the view to load completely. Is there any other efficient way using which the same can be achieved?. I tried partial with collection(like here) as well, but even that did not make much difference in the load time of books. Any suggestions would be highly appreciated. Thanks.

Community
  • 1
  • 1
testsum
  • 51
  • 1
  • 2

5 Answers5

3

Rendering partial in a loop consume too much time because of open/close partial file every iteration. Instead of partial try to use your own helper for this purpose.

Dima Melnik
  • 862
  • 9
  • 23
1

If you have list of values to display in the same view then you can iterate the values in the same view instead of rendering a new partial each time. If it's not the case then it is better to pass values from controller to your view. Hope it helps.

sansarp
  • 1,446
  • 11
  • 18
  • Rendering a plain partial, especially if you pass a `collection`, generally adds an overhead of a few milliseconds. That's not the issue (or nobody would ever use partials). – Simone Carletti Feb 15 '15 at 09:06
1

How about using "proc" on your view top, and then call it in your loop.

<% book_proc = proc do |book| %>
  #your html call
  <% nil %><%# return nil to prevent print out in last string %>
<% end %>

<% books.each do |book| %>
  <%= book_proc.call(book) %>
<% end %>
user1519372
  • 31
  • 1
  • 3
0

You write that you're new to ruby/rails, so have you ever tried using pagination to solve your performance-problem?

A pagination will split your list into parts of e.g. 20 books and sets a paginator mostly at the bottom of your table.

Ingo Plate
  • 31
  • 2
0

I recently worked on a project in which I needed to render a table with about 1000 rows and I obviously experienced performance issues.

When pagination cannot be applied (due to requirements) and speed is required, then helpers is the solution (as already answered by Dima Melnik).

To prove what i said, i give a link to a performance test produced by Ben Scofield: http://viget.com/extend/helpers-vs-partials-a-performance-question

Mauro Nidola
  • 468
  • 4
  • 14