lundi 3 août 2015

Which is faster? Rendering partials or using if-statements?

I have a page that I am rendering which is going to look slightly different depending on who is viewing it. My two options are 1) use some ifs to only display the relevant info and 2) render two different views from my controller based upon who the user is.

In keeping things DRY, I don't want to just render two completely separate pages. Instead, I'd prefer that each page I render both refer to some common partials.

For example:

Option 1

view.slim

h1 Notifications
- if current_user.student.id == params[:id]
  = link_to 'Edit', ...
- @notifications.each do |note|
  # some stuff
h1 Activity
- if current_user.student.id == params[:id]
  = link_to 'Edit', ...
- @activities.each do |note|
  # some stuff
#etc...

Option 2

current_user_view.slim

= render 'notifications_header
= link_to 'Edit', ...
= render 'notifications'

= render 'activities_header
= link_to 'Edit', ...
= render 'activities'

other_user_view.slim

= render 'notifications_header
= render 'notifications'

= render 'activities_header
= render 'activities'

_notifications.slim

- @notifications.each do |note|
  # some stuff

Which is a more efficient approach?

Benchmarks

Here are some benchmarks I did with the following:

_render.slim

- 1000.times do
  = render 'foo'

_foo.slim

| Hello

_if_clause.slim

- 1000.times do
  - if current_user.student.id == params[:id]

With the following results:

benchmarks

So it appears as if rendering partials is extremely slow.

Thoughts?

Rails 4.1.5 ruby 2.1.2

Aucun commentaire:

Enregistrer un commentaire