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)
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With