caching

缓存是性能优化的关键,Claude Code 使用多层缓存机制。

缓存层级

L1: 内存缓存 (最快)

L2: 文件缓存 (快)

L3: API 缓存 (Anthropic Prompt Caching)

内存缓存

System Prompt 缓存

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;
}

工具结果缓存

文件缓存

配置缓存

API 缓存

Anthropic Prompt Caching

缓存失效

TTL (Time To Live)

依赖失效

缓存清理

LRU 策略

下一步