Convert a partial to method/block for speed

后端 未结 6 578
暗喜
暗喜 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:21

    Here is an example from one of my previous answers. It's extracted from PartialRenderer sources.

    - local_names = [:i]
    - partials = {}
    - 1000.times do |i|
      - name = 'name_%s' % (i % 10)
      - partials[name] ||= lookup_context.find_template(name, lookup_context.prefixes, true, local_names)
      = partials[name].render(self, i: i)
    

    I'd recommend you to wrap it with a helper method. Keep in mind that locals' names appear here twice: first in local_names as an array and second in hash's keys passed as the second argument of #render method.

提交回复
热议问题