哪个更快?渲染部分或使用if语句?

时间:2015-08-03 19:27:33

标签: ruby-on-rails ruby if-statement partial-views benchmarking

我有一个我正在渲染的页面,看起来会有所不同,具体取决于谁在查看它。我的两个选项是:1)使用一些ifs仅显示相关信息; 2)根据用户的身份从我的控制器渲染两个不同的视图。

为了保持DRY,我不想只渲染两个完全独立的页面。相反,我更喜欢我呈现的每个页面都引用一些常见的部分。

例如:

选项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...

选项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

哪种方法更有效?

基准

以下是我对以下内容进行的一些基准测试:

_render.slim

- 1000.times do
  = render 'foo'

_foo.slim

| Hello

_if_clause.slim

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

得到以下结果:

benchmarks

因此看起来渲染部分非常慢。

思想?

Rails 4.1.5 红宝石2.1.2

修改1:忘记在| Hello

中添加_if_clause.slim

1 个答案:

答案 0 :(得分:3)

您的基准测试不是在比较相同的功能。 _render一个用字符串渲染1000个部分,_if_clause仅在比较时进行。你应该比较,例如具有内联通知处理的模板呈现和在部分中执行通知处理的模板。

但即使部分渲染速度要慢得多,另外要考虑的是,它是否重要?如果代码更容易理解,则可能值得牺牲一些毫秒的查看时间。

相关问题