Reputation: 1561
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]
| Hello
With the following results:
So it appears as if rendering partials is extremely slow.
Thoughts?
Rails 4.1.5 ruby 2.1.2
Edit 1: Forgot to add the | Hello
line in _if_clause.slim
Upvotes: 3
Views: 650
Reputation: 1424
Your benchmark is not comparing the same functionality. The _render one is rendering 1000 partials with a string, the _if_clause one is doing only if-comparisons. You should compare e.g. a template rendering with inline notification handling and a template doing the notification handling in a partial.
But even if partial rendering should be much slower, the other thing to consider is, does it matter? Depending on your overall performance needs, it may be worth to sacrifice some milliseconds view time, if the code is easier to understand.
Upvotes: 3