Skip to content

7. 性能优化

7.1 延迟加载

typescript
class LazyMemoryLoader {
  private loaded = false;
  private memoryCache: Map<string, MemoryEntry> = new Map();

  // 延迟加载记忆
  async load() {
    if (this.loaded) return;

    // 只加载 MEMORY.md
    const hotMemory = await this.loadHotMemory();
    this.memoryCache.set('hot', hotMemory);

    this.loaded = true;
  }

  // 按需加载主题文件
  async loadTopic(topic: string): Promise<string> {
    if (this.memoryCache.has(topic)) {
      return this.memoryCache.get(topic)!.content;
    }

    const content = await this.loadTopicFile(topic);
    this.memoryCache.set(topic, { content, timestamp: Date.now() });

    return content;
  }

  // 预加载常用主题
  async warmup() {
    const commonTopics = ['debugging', 'patterns'];
    await Promise.all(commonTopics.map(t => this.loadTopic(t)));
  }
}

7.2 增量更新

typescript
class IncrementalMemoryUpdater {
  private pendingUpdates: Map<string, string> = new Map();
  private updateTimer: NodeJS.Timeout | null = null;

  // 添加更新
  add(key: string, content: string) {
    this.pendingUpdates.set(key, content);

    // 延迟批量更新
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
    }

    this.updateTimer = setTimeout(() => {
      this.flush();
    }, 5000);  // 5 秒后批量更新
  }

  // 批量写入
  private async flush() {
    if (this.pendingUpdates.size === 0) return;

    const updates = [...this.pendingUpdates.entries()];
    this.pendingUpdates.clear();

    // 批量写入
    await Promise.all(
      updates.map(([key, content]) =>
        this.writeMemory(key, content)
      )
    );
  }
}

前端面试知识库