Какая строка выполняется дольше всех? $pages =…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Какая строка выполняется дольше всех? id);
// Проверяем, есть ли условия для получения страниц с определенными шаблонами
if (key_exists('templates', $conditions) && is_array($conditions['templates']) && (!key_exists(0, $conditions['templates']) || $conditions['templates'][0] !== '*')) {
$pages = $pages->with(['template', 'template.fieldGroup.fields'])
->whereHas('template', function ($query) use ($conditions) {
$query->whereIn('directory', array_is_list($conditions['templates']) ? $conditions['templates'] : array_keys($conditions['templates']));
});
} else {
// Если нет условий, то просто получаем шаблон и поля
$pages = $pages->with(['template', 'template.fieldGroup.fields']);
}
if (key_exists('filters', $conditions) && is_array($conditions['filters'])) {
foreach ($conditions['filters'] as $fieldName => $filters) {
// FIXME: запрос на то, чтобы получить тип поля, подумать как обойтись без него
$field = Field::query()->where('name', $fieldName)->select(['type'])->first();
$dataField = DataField::getDataField($fieldName, $field->type);
// Валидация опций фильтра
$validatorOptions = $dataField::validFilterOptions("filters.$fieldName", ['filters' => $conditions['filters']]);
if ($validatorOptions->fails()) {
throw new ValidationException($validatorOptions);
}
$safeFilters = $validatorOptions->safe()->toArray();
if (count($safeFilters) > 0) {
$pages = $pages->whereExists(function ($query) use ($safeFilters, $dataField, $fieldName) {
$query->fromSub(
$dataField->filterQuery($safeFilters['filters'][$fieldName])->getQuery(),
"filter_$fieldName"
);
});
}
}
}
$pages = $pages
->orderByRaw('(SELECT sort_order FROM cr_page_tree WHERE cr_page.id = cr_page_tree.fk_child_page LIMIT 1) ASC')
->paginate($conditions['pageSize'] ?? 10);
$pages->appends(['id' => $id]);
$pages->getCollection()->transform(function (Page $page) use ($conditions) {
$templateName = $page->template->directory;
/*
* FIXME: без повторного получения данных будут присваиваться dataField полей первой страницы на последующие
* Баг лары при переборе коллекции
*/
$page->refresh();
// Проверяем, есть ли в шаблоне список разрешенных полей
if (isset($conditions['templates'][$templateName]['fields'])) {
$allowedFields = $conditions['templates'][$templateName]['fields'];
// Проверяем, есть ли у страницы загруженные поля
if ($page->template->fieldGroup && $page->template->fieldGroup->fields) {
$page->template->fieldGroup->fields = $page->template->fieldGroup->fields->whereIn('name', $allowedFields)->values();
} else {
$page->template->fieldGroup->fields = collect();
}
}
// Получение данных полей
foreach ($page->template->fieldGroup->fields as $field) {
$fieldData = DataField::getDataField($field->name, $field->type);
$field->dataField = $fieldData->getData($field, $page);
}
return $page;
});
return $pages;
Чтобы определить, какая строка выполняется дольше всех в вашем коде, можно использовать Laravel Debugbar, Telescope или ручное профилирование. Давайте разберём возможные "узкие места" в вашем коде и способы их измерения.
Из вашего кода можно выделить несколько частей, которые могут быть медленными:
Запросы к базе данных:
Page::query()->whereRelation(...)$pages->with(['template', 'template.fieldGroup.fields']) (жадная загрузка)$pages->whereHas('template', ...)Field::query()->where('name', $fieldName)->select(['type'])->first() (выполняется в цикле)$dataField->filterQuery(...) (подзапрос в whereExists)orderByRaw('(SELECT sort_order FROM cr_page_tree ...) ASC') (подзапрос в сортировке)paginate() (может быть медленным при большом количестве записей)Обработка коллекции:
$pages->getCollection()->transform(...) (особенно $page->refresh() и DataField::getDataField() в цикле)Жадная загрузка (with) и подзапросы (whereHas, whereExists):
Debugbar::measure()use Debugbar;
Debugbar::startMeasure('total', 'Общее время выполнения');
// Запрос страниц
Debugbar::startMeasure('query_pages', 'Запрос страниц');
$pages = Page::query()->whereRelation('pageParent', 'fk_parent_page', $id);
Debugbar::stopMeasure('query_pages');
// Проверка шаблонов
if (key_exists('templates', $conditions) && is_array($conditions['templates']) && (!key_exists(0, $conditions['templates']) || $conditions['templates'][0] !== '*')) {
Debugbar::startMeasure('query_templates', 'Запрос шаблонов');
$pages = $pages->with(['template', 'template.fieldGroup.fields'])
->whereHas('template', function ($query) use ($conditions) {
$query->whereIn('directory', array_is_list($conditions['templates']) ? $conditions['templates'] : array_keys($conditions['templates']));
});
Debugbar::stopMeasure('query_templates');
} else {
Debugbar::startMeasure('query_templates_simple', 'Простая загрузка шаблонов');
$pages = $pages->with(['template', 'template.fieldGroup.fields']);
Debugbar::stopMeasure('query_templates_simple');
}
// Фильтрация
if (key_exists('filters', $conditions) && is_array($conditions['filters'])) {
foreach ($conditions['filters'] as $fieldName => $filters) {
Debugbar::startMeasure('query_field_type', 'Получение типа поля');
$field = Field::query()->where('name', $fieldName)->select(['type'])->first();
Debugbar::stopMeasure('query_field_type');
$dataField = DataField::getDataField($fieldName, $field->type);
// Валидация и фильтрация
Debugbar::startMeasure('query_filter', 'Фильтрация по полю');
$pages = $pages->whereExists(function ($query) use ($filters, $dataField, $fieldName) {
$query->fromSub(
$dataField->filterQuery($filters['filters'][$fieldName])->getQuery(),
"filter_$fieldName"
);
});
Debugbar::stopMeasure('query_filter');
}
}
// Сортировка и пагинация
Debugbar::startMeasure('query_order_paginate', 'Сортировка и пагинация');
$pages = $pages
->orderByRaw('(SELECT sort_order FROM cr_page_tree WHERE cr_page.id = cr_page_tree.fk_child_page LIMIT 1) ASC')
->paginate($conditions['pageSize'] ?? 10);
Debugbar::stopMeasure('query_order_paginate');
// Обработка коллекции
Debugbar::startMeasure('collection_transform', 'Обработка коллекции');
$pages->getCollection()->transform(function (Page $page) use ($conditions) {
// ...
});
Debugbar::stopMeasure('collection_transform');
Debugbar::stopMeasure('total');
Log$start = microtime(true);
$pages = Page::query()->whereRelation('pageParent', 'fk_parent_page', $id);
Log::info('whereRelation: ' . (microtime(true) - $start) . ' сек');
$start = microtime(true);
$pages = $pages->with(['template', 'template.fieldGroup.fields']);
Log::info('with: ' . (microtime(true) - $start) . ' сек');
// и так далее...
Если у вас установлен Telescope, он автоматически логирует все SQL-запросы и их время выполнения.
orderByRaw с подзапросом
->orderByRaw('(SELECT sort_order FROM cr_page_tree WHERE cr_page.id = cr_page_tree.fk_child_page LIMIT 1) ASC')
cr_page_tree.fk_child_page или переписать запрос с JOIN.whereExists с подзапросом
$pages = $pages->whereExists(function ($query) use ($safeFilters, $dataField, $fieldName) {
$query->fromSub(
$dataField->filterQuery($safeFilters['filters'][$fieldName])->getQuery(),
"filter_$fieldName"
);
});
$conditions['filters'] содержит много полей, это создаст много подзапросов.filterQuery или использовать кэширование.Field::query()->where('name', $fieldName)->first() в цикле
$page->refresh() в transform
with).DataField::getDataField() в цикле
getDataField делает запросы к БД, это замедлит обработку.EXPLAIN для анализа).orderByRaw на JOIN:
$pages = $pages->join('cr_page_tree', 'cr_page.id', '=', 'cr_page_tree.fk_child_page')
->orderBy('cr_page_tree.sort_order', 'ASC');
refresh() (загружать все данные заранее).Field:
$fields = Field::query()->whereIn('name', array_keys($conditions['filters']))->pluck('type', 'name');
chunk или cursor при работе с большими коллекциями.Скорее всего, самые медленные строки — это orderByRaw с подзапросом и whereExists в цикле. Используйте Debugbar или Telescope, чтобы точно измерить время выполнения каждого участка кода.