Partial method / block conversion for speed

I have a loop that displays partial

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

it is very slow, up to 0.1 ms for calling foreach rendering, even if partial only outputs i

my_partial = render_to_method(partial: 'test')
1000.times do |i|
  my_partial(locals: {i: i})
end

Now should this do the same thing faster faster? But I do not know how to do this.

update:

I tried to do it like this:

Haml::Engine.new(File.read(File.expand_path File.dirname(FILE)+"/../table/#{column.macro}/_#{column.display_type}.haml"))
.‌​render(OpenStruct.new({column_value: column_value, object: object})) 

two main disadvantages:

  • The view path will not look at the backups, as it happens when you do this using rendering (parital: "partial" will search for parital in the current dir view, in some gems, as well as in the view / application.
  • Rails view helpers are no longer available

update 2:

, . . https://github.com/antpaw/bhf/blob/master/app/views/bhf/pages/_platform.haml#L54 , , , main_app. , , : 1. . 2. . (3. .)

3:

@Flash https://gist.github.com/antpaw/d6670c23d6f08e35812e#file-gistfile1-haml-L54

template = lookup_context.find_template "#{column.macro}/#{column.display_type}", ['bhf/table'], true
template.render(self, {column_value: column_value, object: object})

locals. , , .

+4
6

. PartialRenderer .

- 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)

. , : local_names , - -, #render.

+2

, " "

:

  • - ,
  • - 1000- , , B

Bs:

PS ? https://github.com/apotonick/cells
+5

, , . , response , , (<<) stream response. response#body .

- my_partial. View, , , response . , , , .

, , , , .

0

content_tag. , .

def my_partial(i)
  content_tag(:div, i, class: 'iterator')
end

content_tag, , , , .

: , , , . , .

:

# index.html.erb
<%= render partial: 'dogs', locals: {dogs: @dogs} %>

# show.html.erb
<%= render partial: 'dogs', locals: {dogs: [@dog]} %>

# _dogs.html.erb
<% dogs.each do |dog| %>
  <%= dog.name %>
<% end %>
0

If you need to do it many times and it is slow, I suggest you do not call it rendermany times. I know, I'm an obvious captain.

If it localscontains simple strings or numbers, try to make the view once, and then just replace the parts with real variables.

text = render(partial: 'test', locals: {i: '$'})

1000.times do |i|
  output[i] = text.gsub('$', i)
end
0
source

Source: https://habr.com/ru/post/1544711/


All Articles