Which is faster? Providing partial data or using if statements?
I have a page that I present that will look slightly different depending on who is viewing it. My two options are 1)
only use some to display relevant information and 2) display two different views from my controller based on who the user is.
Keeping things DRY, I don't want to just display two completely separate pages. Instead, I would prefer that every page I submit link to some common partials.
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...
= render 'notifications_header = link_to 'Edit', ... = render 'notifications' = render 'activities_header = link_to 'Edit', ... = render 'activities'
= render 'notifications_header = render 'notifications' = render 'activities_header = render 'activities'
- @notifications.each do |note| # some stuff
What's the more efficient approach?
Here are some tests I did with the following:
- 1000.times do = render 'foo'
- 1000.times do - if current_user.student.id == params[:id] | Hello
With the following results:
So it seems that the partial rendering parts are very slow.
Rails 4.1.5 ruby 2.1.2
Edit 1: Forgot to add the line
source to share
Your test will not compare the same functionality. _render is the rendering of 1000 particles with a string, and _if_clause is only for comparison. You have to compare for example. a template rendering with inline notification handling; and a template that does partial notification handling.
But even if partial rendering is supposed to be much slower, another thing to consider is whether it matters? Depending on your overall performance needs, it might be worth sacrificing millisecond lookup times if the code is easier to understand.
source to share