Convert a partial to method/block for speed

后端 未结 6 574
暗喜
暗喜 2021-02-06 13:46

I have a loop that renders a partial

1000.times do |i|
  render partial: \'test\', locals: {i: i}
end

this is really slow, up to 0.1 ms for for

6条回答
  •  不思量自难忘°
    2021-02-06 14:35

    I love this question, but it may be a "wrong tool for the job" thing

    Basically:

    1. if the partial is simple - consider not using a partial at all, the overhead isn't worth it
    2. if the partial is complex - then rendering 1000s of things will take TIME out of which partial overhead is just a fraction of, you'll need a plan B

    Plan Bs:

    1. render 25-50-100.... thingies at first and fetch additional records from the server as the user scrolls - http://railscasts.com/episodes/114-endless-page
    2. send a JSON array from the server and let client side JS iterate through the collection and render HTML - this way the partial template can still be rendered in rails and client side JS can do gsub
    3. cache everything you possibly can - this doesn't include forms unfortunately which are typically the slowest rendering components
    4. ...

    PS have you tried out cells? https://github.com/apotonick/cells

提交回复
热议问题