Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: why is one way of rendering partials so much faster?

I'm not sure if this is a Rails specific issue, hence the reason I tagged it ruby as well.

I'm rendering a collection of event records via a partial. However, I found that rendering the partial differently results in drastic performance differences.

Both version use the exact same data, the only thing changing is the code used to render the partials.

Why the heck is one version consistently 4x faster than the other? Makes me wonder what other performance hits I'm taking...

Slow version (950ms total request time):

<% events.each do |event| %>
  <%= render partial: "events/event", locals: { event: event } %>
<% end %>

# Log output
Rendered events/_event.html.erb (1.1ms)
Rendered events/_event.html.erb (1.1ms) 
...

Faster version (250ms total request time):

<%= render partial: "events/event", collection: events, as: :event %>

# Log output
Rendered events/_event.html.erb (58.7ms)
like image 226
Dan L Avatar asked Jun 12 '17 23:06

Dan L


People also ask

What is the reason for having partials in Rails?

Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates. Partials are also useful when you need to reuse exactly the same code (DRY philosophy).

What is the partial render in the rails?

Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

What is the use of render in rails?

Rails can render a raw file from an absolute path. This is useful for conditionally rendering static files like error pages. This renders the raw file (it doesn't support ERB or other handlers). By default it is rendered within the current layout.


1 Answers

example 1: you are rendering a partial x times (depending on events). which means you are compiling html x times(once each time the loop runs). which is slow

example 2: you are rendering one partial with a collection of events the html is compiled once(as there is only one partial). which is fast

like image 53
amateur-programateur Avatar answered Sep 21 '22 00:09

amateur-programateur