Skip to content

Conversation

@darialapina
Copy link

Задача

Импорт данных

Ускорить загрузку данных из json в БД
Необходимо загрузить файл large.json размером ~32Мб. Загрузка занимает неопределенное время, так как дождаться её окончания не хватает терпения.
Проверка ускорения работы скрипта будет производиться на файлах меньшего размера, для получения быстрого feedback-loop'a.

Для неоптимизированного скрипта:

== Loading data from fixtures/small.json ==
0.000156 0.000983 8.520823 ( 10.306963)

== Loading data from fixtures/medium.json ==
0.000148 0.000870 55.193750 ( 66.966470)

Оптимизация

После проведения оптимизации были получены следующие времена для файлов небольшого размера

== Loading data from fixtures/small.json ==
0.000164 0.001091 1.426264 ( 1.390508)

== Loading data from fixtures/medium.json ==
0.000155 0.001073 3.516669 ( 3.664605)

И удалось выполнить загрузку файла large.json менее, чем за минуту

== Loading data from fixtures/large.json ==
0.000182 0.001019 22.925601 ( 25.104676)

Отображение расписаний

Сами страницы расписаний тоже формируются не эффективно и при росте объёмов начинают сильно тормозить.
Для замера времени рендеринга страницы буду использовать гем rack-mini-profiler.
Заодно он даст мне информацию по проблемным местам.

До оптимизации:

before

Видно, что имеется проблема N+1 запросов при рендеринге паршалов.
Так же в коде сразу видно, что при рендеринге коллекций используется вызов рендеринга partial'a в цилке, когда как оптимальнее передать коллекцию в partial.
Также имеет смысл добавить индексы в БД. Помимо умкорения выборок они подстрахуют уникальность данных.

После оптимизации:

after

Copy link
Owner

@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.

Approve + some comments.

@@ -0,0 +1 @@
--require spec_helper
Copy link
Owner

Choose a reason for hiding this comment

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

👍

gem 'puma', '~> 3.11'
gem 'bootsnap', '>= 1.1.0', require: false

gem 'pghero'
Copy link
Owner

Choose a reason for hiding this comment

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

👍

gem 'bootsnap', '>= 1.1.0', require: false

gem 'pghero'
gem 'activerecord-import'
Copy link
Owner

Choose a reason for hiding this comment

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

👍

has_many :trips
has_and_belongs_to_many :services, join_table: :buses_services
has_many :buses_services
has_many :services, through: :buses_services
Copy link
Owner

Choose a reason for hiding this comment

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

👍

@@ -0,0 +1,16 @@
class AddIndexes < ActiveRecord::Migration[5.2]
def change
add_index :cities, :name, unique: true
Copy link
Owner

Choose a reason for hiding this comment

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

👍 плюсик за уникальность

@@ -0,0 +1,61 @@
# This file is copied to spec/ when you run 'rails generate rspec:install'
Copy link
Owner

Choose a reason for hiding this comment

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

А тестов нет?

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