diff --git a/packages/vite/src/node/plugins/index.ts b/packages/vite/src/node/plugins/index.ts index 08bb7c3a99c3a8..fc230c686641b1 100644 --- a/packages/vite/src/node/plugins/index.ts +++ b/packages/vite/src/node/plugins/index.ts @@ -140,27 +140,30 @@ export function getSortedPluginsByHook( hookName: K, plugins: readonly Plugin[], ): PluginWithRequiredHook[] { - 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[] + return sortedPlugins as PluginWithRequiredHook[] } export function getHookHandler>(