Rails Rails 3, render partial 有 bug 还是代码错误?

michael_roshen · 2014年03月03日 · 最后由 yangman_wenzhu 回复于 2015年02月02日 · 2619 次阅读

ruby: 1.8.7 rails: 3.0.4

在 search_right.html.erb 中,render partial 时候,本机基本在 1ms 左右,但是偶尔会有一个 partial 渲染的时间 特别长,这里竟然达到了 223ms, 而且不固定会出现在那一个 item 的渲染上,是不是 rails 的 bug?

search_right.html.erb:

<% @paginated_hits.each_with_index do |hit, index| %>
  <%= render :partial => "search/search_item",:locals => {:hit => hit,:index =>index} %>
<% end %>

search_item.html.erb:

<tr>
  <td> "test" </td>
</tr>

查看 log 信息如下:

16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.8ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.6ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.7ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.6ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.7ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.7ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (1.4ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.9ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.8ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.6ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.7ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (223.0ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.9ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.9ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (1.0ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (1.0ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (1.0ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (1.1ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (1.0ms)
16:08:52 action_view_Rendered search/_product_search_item.html.erb (0.9ms)
16:08:52 action_view_Rendered search/_product_search_right.html.erb (378.9ms)

不固定出现?会不会是碰上 gc 的停顿了?

#1 楼 @alsotang google 到说是 gc 的问题,尚不清楚啊

#3 楼 @ruby_sky 漂亮!我测试了一下,速度竟然快了 4 倍,谢谢!

#3 楼 @ruby_sky

<% @paginated_hits.each_with_index do |hit, index| %>
    <%= render :partial => "search/product_search_item",:locals => {:hit => hit,:index =>index} %>
<% end %>

请教个问题:如何能把 index 也传到 partial 中去

<%= render :partial => "search/product_search_item", :collection => @paginated_hits, :as => :hit, :locals => {:hit => :hit, :index => ???? } %>

#5 楼 @michael_roshen 直接把 collection 传到你的 partial 里,然后在 partial 里循环。或者在现有实现中其他更好的方法,要 debugger 一下。

下次 ruby 聚会的时候,可以分享一个相关方面优化的主题

#7 楼 @leopku 简单的测试到时快乐许多,但是我们的项目上速度还是上不来,看了源代码,传 collection 他也是个循环,两种调用的都是@template.render。搞清楚了肯定分享!

#8 楼 @michael_roshen 请问你这个 :locals => {:hit => hit,:index =>index} 传递参数的形式,后面的 partial 可以使用你的 index 参数么? https://ruby-china.org/topics/24069 请帮忙看下这个问题咯😄

需要 登录 后方可回复, 如果你还没有账号请 注册新账号