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

perf: optimize getSortedPluginsByHook #15624

Merged
merged 1 commit into from
Jan 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,27 +140,30 @@ export function getSortedPluginsByHook<K extends keyof Plugin>(
hookName: K,
plugins: readonly Plugin[],
): PluginWithRequiredHook<K>[] {
const pre: Plugin[] = []
const normal: Plugin[] = []
const post: Plugin[] = []
const sortedPlugins: Plugin[] = []
// Use indexes to track and insert the ordered plugins directly in the
// resulting array to avoid creating 3 extra temporary arrays per hook
let pre = 0,
normal = 0,
post = 0
for (const plugin of plugins) {
const hook = plugin[hookName]
if (hook) {
if (typeof hook === 'object') {
if (hook.order === 'pre') {
pre.push(plugin)
sortedPlugins.splice(pre++, 0, plugin)
continue
}
if (hook.order === 'post') {
post.push(plugin)
sortedPlugins.splice(pre + normal + post++, 0, plugin)
continue
}
}
normal.push(plugin)
sortedPlugins.splice(pre + normal++, 0, plugin)
}
}

return [...pre, ...normal, ...post] as PluginWithRequiredHook<K>[]
return sortedPlugins as PluginWithRequiredHook<K>[]
}

export function getHookHandler<T extends ObjectHook<Function>>(
Expand Down