Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perform optimization #110

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Conversation

Franerial
Copy link

No description provided.

Copy link
Collaborator

@spajic spajic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 nice work!

# frozen_string_literal: true

module Tasks
class ImportJsonData
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лайк за сервис

str = +''

until ff.eof?
ch = ff.read(1) # читаем по одному символу
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 лайк за стриминг, мало кто делает

<% end %>
</ul>

====================================================
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот этот разделитель можно тоже параметром задать (забавный факт: https://guides.rubyonrails.org/layouts_and_rendering.html#spacer-templates)

@@ -2,15 +2,7 @@
<%= "Автобусы #{@from.name} – #{@to.name}" %>
</h1>
<h2>
<%= "В расписании #{@trips.count} рейсов" %>
<%= "В расписании #{@trips.length} рейсов" %>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лично я за size )

Нужно применить подход с BATCH INSERT. Для этого использовался гем **activerecord-import**. Основная проблема была импортировать связи, т.к
требуется внешний ключ, т.е знание id непосредственно на уровне бд. Чтобы не делать лишних SELECT запросов, использовал хранение id автобусов, городов и сервисов в хеше на уровне оперативной памяти (хеш обновлялся каждый раз при добавлении новых объектов в базу)

Также добавлял индексы (в том числе и составные) на уникальность, т.к при BATCH INSERT возможно появления дубликатов и нужна валидация на уровне бд
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

кстати говоря, индексы лучше в таком случае накидывать после импорта

может иметь смысл даже такой флоу

  • удалили индекс
  • импортнули данные
  • создали индекс (если не создался - увы, что-то не так пошло с импортом)

зависит от использования конечно; но поинт в том, что вставки в базе идут быстрее когда не приходится индекс обновлять / проверять / поддерживать

- видна долгая загрузка partial _trip.html.erb и _service.html.erb
- удалил конструкцию с `@trips.each` и переписал на более быстрый подход рендера с конструкцией `render partial: "trip", collection: @trips`
- аналогично для сервисов: `<%= render partial: "service", collection: trip.bus.services %>`
- рендер страницы ускорился с 2.7 секунд до 500мс
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

### Находка №4
- Рендер вьюх всё ещё занимал основное время
- Дропнул ненужную вьюху `_delimiter.html.erb` и просто вставил текст из неё в родительскую вьюху `_trip.html.erb`
- рендер страницы ускорился с 500мс до 260мс
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


```

-> получилось добиться открытия страницы за 263мс
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

там ещё индексы на таблицы можно создать было бы; с точки зрения времени загрузки это не топ проблема, но с точки зрения нагрузки на базу - да; и это идёт как use-case pg-hero, так как он прям пишет какие индексы надо создать

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants