|
| 1 | +import { performance } from 'node:perf_hooks'; |
| 2 | + |
| 3 | +// Simulate the old way |
| 4 | +async function resolvePluginReference(pluginRef) { |
| 5 | + // simulate I/O delay |
| 6 | + return new Promise(resolve => setTimeout(() => resolve(pluginRef + '-resolved'), 10)); |
| 7 | +} |
| 8 | + |
| 9 | +async function findRegisteredPluginIndexOld(plugins, pluginRef) { |
| 10 | + const resolvedPluginRef = await resolvePluginReference(pluginRef); |
| 11 | + |
| 12 | + for (const [index, registeredPlugin] of plugins.entries()) { |
| 13 | + const resolvedRegisteredPlugin = await resolvePluginReference(registeredPlugin); |
| 14 | + if (resolvedRegisteredPlugin === resolvedPluginRef) { |
| 15 | + return index; |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + return -1; |
| 20 | +} |
| 21 | + |
| 22 | +// Simulate the new way |
| 23 | +async function findRegisteredPluginIndexNew(plugins, pluginRef) { |
| 24 | + const resolvedPluginRef = await resolvePluginReference(pluginRef); |
| 25 | + |
| 26 | + const resolvedPlugins = await Promise.all(plugins.map(plugin => resolvePluginReference(plugin))); |
| 27 | + |
| 28 | + for (const [index, resolvedRegisteredPlugin] of resolvedPlugins.entries()) { |
| 29 | + if (resolvedRegisteredPlugin === resolvedPluginRef) { |
| 30 | + return index; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return -1; |
| 35 | +} |
| 36 | + |
| 37 | +const plugins = Array.from({length: 100}, (_, i) => `plugin-${i}`); |
| 38 | +const target = 'plugin-99'; // Worst case |
| 39 | + |
| 40 | +async function run() { |
| 41 | + const startOld = performance.now(); |
| 42 | + await findRegisteredPluginIndexOld(plugins, target); |
| 43 | + const endOld = performance.now(); |
| 44 | + console.log(`Old: ${endOld - startOld} ms`); |
| 45 | + |
| 46 | + const startNew = performance.now(); |
| 47 | + await findRegisteredPluginIndexNew(plugins, target); |
| 48 | + const endNew = performance.now(); |
| 49 | + console.log(`New: ${endNew - startNew} ms`); |
| 50 | +} |
| 51 | + |
| 52 | +run(); |
0 commit comments