startup
优化目标
多级 Fast-Path
1
2
代码分割
动态导入
// 主入口只加载核心模块
async function main() {
const { query } = await import('./query');
const { tools } = await import('./tools');
// 启动 UI
await startUI(query, tools);
}// 主入口只加载核心模块
async function main() {
const { query } = await import('./query');
const { tools } = await import('./tools');
// 启动 UI
await startUI(query, tools);
}// 只在需要时加载
if (options.enableBridge) {
const { initBridge } = await import('./bridge');
await initBridge();
}
if (options.enableMCP) {
const { loadMCPServers } = await import('./services/mcp');
await loadMCPServers();
}let configCache: Config | null = null;
async function loadConfig(): Promise<Config> {
if (configCache) {
return configCache;
}
const config = await readConfigFile();
configCache = config;
return config;
}const promptCache = new Map<string, string>();
async function getSystemPrompt(tools: Tool[]): Promise<string> {
const key = hashTools(tools);
if (promptCache.has(key)) {
return promptCache.get(key);
}
const prompt = await buildSystemPrompt(tools);
promptCache.set(key, prompt);
return prompt;
}// ❌ 同步读取(阻塞)
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
// ✅ 异步读取(非阻塞)
const config = JSON.parse(await fs.readFile('config.json', 'utf-8'));// ❌ 串行读取
const file1 = await fs.readFile('file1.txt');
const file2 = await fs.readFile('file2.txt');
const file3 = await fs.readFile('file3.txt');
// ✅ 并行读取
const [file1, file2, file3] = await Promise.all([
fs.readFile('file1.txt'),
fs.readFile('file2.txt'),
fs.readFile('file3.txt'),
]);# 构建
bun build src/main.tsx --outdir dist --target node
# 启动预编译版本
node dist/main.jsasync function optimizedStartup() {
const startTime = performance.now();
// 1. 最小化初始化
const coreModules = await import('./core');
// 2. 并行预取
const [config, state] = await Promise.all([
loadConfig(),
loadState(),
]);
// 3. 启动 UI(不等待完整加载)
startUI();
// 4. 后台加载其他模块
Promise.all([
loadSkills(),
loadPlugins(),
connectMCPServers(),
]).then(() => {
console.log('All modules loaded');
});
const duration = performance.now() - startTime;
console.log(`Startup: ${duration}ms`);
}const timings = {
import: 0,
config: 0,
state: 0,
ui: 0,
total: 0,
};
async function measureStartup() {
const start = performance.now();
// 导入
const t1 = performance.now();
await import('./core');
timings.import = performance.now() - t1;
// 配置
const t2 = performance.now();
await loadConfig();
timings.config = performance.now() - t2;
// 状态
const t3 = performance.now();
await loadState();
timings.state = performance.now() - t3;
// UI
const t4 = performance.now();
await startUI();
timings.ui = performance.now() - t4;
timings.total = performance.now() - start;
console.table(timings);
}