Skip to content

Commit

Permalink
perf: optimize getSortedPluginsByHook (#15624)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev authored Jan 19, 2024
1 parent f3c11bb commit f08a037
Showing 1 changed file with 10 additions and 7 deletions.
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

0 comments on commit f08a037

Please sign in to comment.