Ускорение загрузки данных и отображения расписания#5
Open
darialapina wants to merge 2 commits intospajic:masterfrom
Open
Ускорение загрузки данных и отображения расписания#5darialapina wants to merge 2 commits intospajic:masterfrom
darialapina wants to merge 2 commits intospajic:masterfrom
Conversation
spajic
approved these changes
Apr 7, 2019
| @@ -0,0 +1 @@ | |||
| --require spec_helper | |||
| gem 'puma', '~> 3.11' | ||
| gem 'bootsnap', '>= 1.1.0', require: false | ||
|
|
||
| gem 'pghero' |
| gem 'bootsnap', '>= 1.1.0', require: false | ||
|
|
||
| gem 'pghero' | ||
| gem 'activerecord-import' |
| has_many :trips | ||
| has_and_belongs_to_many :services, join_table: :buses_services | ||
| has_many :buses_services | ||
| has_many :services, through: :buses_services |
| @@ -0,0 +1,16 @@ | |||
| class AddIndexes < ActiveRecord::Migration[5.2] | |||
| def change | |||
| add_index :cities, :name, unique: true | |||
| @@ -0,0 +1,61 @@ | |||
| # This file is copied to spec/ when you run 'rails generate rspec:install' | |||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Задача
Импорт данных
Ускорить загрузку данных из 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.
Заодно он даст мне информацию по проблемным местам.
До оптимизации:
Видно, что имеется проблема N+1 запросов при рендеринге паршалов.
Так же в коде сразу видно, что при рендеринге коллекций используется вызов рендеринга partial'a в цилке, когда как оптимальнее передать коллекцию в partial.
Также имеет смысл добавить индексы в БД. Помимо умкорения выборок они подстрахуют уникальность данных.
После оптимизации: