fox-optimize

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Fox Optimize 🦊

Fox Optimize 🦊

The fox doesn't lumber through the forest. It moves with swift precision, finding the fastest paths between trees. When something slows the hunt, the fox notices immediately. It stalks the problem, isolates it, and strikes. The forest flows better after the fox passes through.
狐狸不会在森林里蹒跚而行。它行动精准迅捷,总能找到树木间最快的路径。当有事物拖慢捕猎节奏时,狐狸会立刻察觉。它追踪问题、隔离问题并解决问题。狐狸经过后,森林的运转会更加顺畅。

When to Activate

激活场景

  • User asks to "optimize this" or "make it faster"
  • User says "it's slow" or "performance issue"
  • User calls
    /fox-optimize
    or mentions fox/performance
  • Page load times are unacceptable
  • Database queries are sluggish
  • Bundle size is too large
  • Memory leaks detected
  • Animations are janky
  • API response times are slow
Pair with:
bloodhound-scout
to find slow code paths

  • 用户要求「优化这段代码」或「让它更快」
  • 用户反馈「运行缓慢」或「存在性能问题」
  • 用户调用
    /fox-optimize
    或提及 fox/performance
  • 页面加载时间过长
  • 数据库查询速度迟缓
  • 包体积过大
  • 检测到内存泄漏
  • 动画出现卡顿
  • API响应时间过长
搭配工具:
bloodhound-scout
用于定位缓慢代码路径

The Hunt

优化流程

STALK → PINPOINT → STREAMLINE → CATCH → CELEBRATE
   ↓         ↲           ↲           ↓          ↓
Watch for  Find the    Optimize   Capture   Enjoy the
Slowness   Bottleneck  Hot Paths  Gains     Win
STALK → PINPOINT → STREAMLINE → CATCH → CELEBRATE
   ↓         ↲           ↲           ↓          ↓
Watch for  Find the    Optimize   Capture   Enjoy the
Slowness   Bottleneck  Hot Paths  Gains     Win

Phase 1: STALK

阶段1:STALK(追踪)

The fox pads silently, watching for what moves too slowly...
Identify where performance matters:
What feels slow?
  • Initial page load (First Contentful Paint)
  • Interactions (Time to Interactive)
  • Scrolling (frame drops)
  • Data loading (API latency)
  • Transitions (animation jank)
Measure before optimizing:
bash
undefined
狐狸悄然潜行,留意所有行动迟缓的事物……
确定性能影响关键区域:
哪些环节运行缓慢?
  • 初始页面加载(First Contentful Paint)
  • 交互响应(Time to Interactive)
  • 滚动流畅度(帧丢失)
  • 数据加载(API延迟)
  • 过渡动画(动画卡顿)
优化前先测量:
bash
undefined

Web vitals

Web vitals

npm install -g lighthouse lighthouse https://yoursite.com --output=json
npm install -g lighthouse lighthouse https://yoursite.com --output=json

Bundle analysis

包体积分析

npm run build npm run analyze
npm run build npm run analyze

Database query times

数据库查询时间

Check your ORM's query logging

检查ORM的查询日志


**Set a target:**

- First Contentful Paint: < 1.8s
- Time to Interactive: < 3.8s
- API response: < 200ms (p95)
- Animation: 60fps consistently

**Output:** Baseline metrics and target goals defined

---

**设定目标:**

- First Contentful Paint: < 1.8s
- Time to Interactive: < 3.8s
- API响应时间: < 200ms (p95)
- 动画帧率: 稳定60fps

**输出结果:** 明确基准指标与目标值

---

Phase 2: PINPOINT

阶段2:PINPOINT(定位)

Ears perk. The fox isolates exactly where the prey hides...
Find the bottleneck:
Frontend Performance:
javascript
// Chrome DevTools Performance tab
// Look for:
// - Long tasks (>50ms)
// - Layout thrashing (forced reflows)
// - Memory leaks (growing heap)

// Lighthouse report flags:
// - Unused JavaScript
// - Render-blocking resources
// - Unoptimized images
// - Third-party scripts
Database Queries:
sql
-- Find slow queries (SQLite example)
-- Enable query logging in your ORM

-- Check for missing indexes
EXPLAIN QUERY PLAN
SELECT * FROM posts WHERE tenant_id = 'x' AND status = 'published';
-- Look for "SCAN" instead of "SEARCH" - needs index

-- Add index
CREATE INDEX idx_posts_tenant_status ON posts(tenant_id, status);
Bundle Analysis:
bash
undefined
狐狸竖起耳朵,精准锁定问题根源……
定位性能瓶颈:
前端性能:
javascript
// Chrome DevTools Performance面板
// 重点关注:
// - 长任务(>50ms)
// - 布局抖动(强制重排)
// - 内存泄漏(堆内存持续增长)

// Lighthouse报告标记:
// - 未使用的JavaScript
// - 阻塞渲染的资源
// - 未优化的图片
// - 第三方脚本
数据库查询:
sql
-- 查找慢查询(SQLite示例)
-- 在ORM中启用查询日志

-- 检查缺失的索引
EXPLAIN QUERY PLAN
SELECT * FROM posts WHERE tenant_id = 'x' AND status = 'published';
-- 若显示"SCAN"而非"SEARCH",则需要添加索引

-- 添加索引
CREATE INDEX idx_posts_tenant_status ON posts(tenant_id, status);
包体积分析:
bash
undefined

Visualize what's in your bundle

可视化包内内容

npm install --save-dev rollup-plugin-visualizer
npm install --save-dev rollup-plugin-visualizer

Add to vite.config.ts

添加到vite.config.ts

import { visualizer } from 'rollup-plugin-visualizer';
plugins: [ visualizer({ open: true }) ]
import { visualizer } from 'rollup-plugin-visualizer';
plugins: [ visualizer({ open: true }) ]

Look for:

重点关注:

- Large dependencies (can you tree-shake?)

- 大型依赖(是否支持tree-shake?)

- Duplicate code

- 重复代码

- Unnecessary polyfills

- 不必要的polyfill


**Common Bottlenecks:**

| Area         | Common Issues                                         |
| ------------ | ----------------------------------------------------- |
| **Frontend** | Unoptimized images, blocking JS, large bundles        |
| **Database** | Missing indexes, N+1 queries, full table scans        |
| **API**      | Synchronous blocking, no caching, heavy computation   |
| **Network**  | Too many requests, no compression, large payloads     |
| **Memory**   | Leaks from unsubscribed listeners, retained DOM nodes |

**Output:** Specific bottleneck identified with evidence

---

**常见瓶颈:**

| 领域         | 常见问题                                         |
| ------------ | ----------------------------------------------------- |
| **前端** | 未优化的图片、阻塞式JS、过大的包体积        |
| **数据库** | 缺失索引、N+1查询、全表扫描        |
| **API**      | 同步阻塞、无缓存、繁重计算   |
| **网络**  | 请求过多、未压缩、过大的负载     |
| **内存**   | 未取消订阅的监听器、残留DOM节点导致的泄漏 |

**输出结果:** 定位到具体瓶颈并提供证据

---

Phase 3: STREAMLINE

阶段3:STREAMLINE(优化)

The fox finds the fastest path through the thicket...
Apply targeted optimizations:
Image Optimization:
svelte
<!-- Use proper formats and sizes -->
<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Description" loading="lazy" decoding="async">
</picture>

<!-- Or use a component -->
<OptimizedImage
  src="photo.jpg"
  alt="Description"
  widths={[400, 800, 1200]}
  sizes="(max-width: 800px) 100vw, 800px"
/>
Code Splitting:
typescript
// Before: Everything in main bundle
import HeavyChart from './HeavyChart.svelte';

// After: Lazy load
const HeavyChart = lazy(() => import('./HeavyChart.svelte'));

// Or in SvelteKit
{#await import('./HeavyChart.svelte') then { default: HeavyChart }}
  <HeavyChart data={chartData} />
{/await}
Database Optimization:
typescript
// Before: N+1 query problem
const posts = await db.query.posts.findMany();
for (const post of posts) {
  post.author = await db.query.users.findFirst({
    where: eq(users.id, post.authorId),
  });
}

// After: Single query with join
const postsWithAuthors = await db.query.posts.findMany({
  with: {
    author: true,
  },
});
Caching Strategy:
typescript
// API route caching
export const GET: RequestHandler = async ({ platform }) => {
  const cache = platform?.env?.CACHE;
  const cacheKey = "popular-posts";

  // Check cache first
  let data = await cache?.get(cacheKey);
  if (data) {
    return json(JSON.parse(data));
  }

  // Fetch fresh
  data = await fetchPopularPosts();

  // Cache for 5 minutes
  await cache?.put(cacheKey, JSON.stringify(data), { expirationTtl: 300 });

  return json(data);
};
Memoization:
svelte
<script>
  import { memoize } from '$lib/utils/memoize';

  // Expensive computation
  const calculateStats = memoize((data) => {
    return data.reduce(/* complex logic */);
  });

  // Only recalculates when data changes
  $: stats = calculateStats($dataStore);
</script>
Virtual Scrolling:
svelte
<!-- For long lists -->
<VirtualList items={largeArray} let:item>
  <ListItem {item} />
</VirtualList>

<!-- Only renders visible items -->
Output: Optimizations applied with minimal code changes

狐狸找到穿过灌木丛的最快路径……
实施针对性优化:
图片优化:
svelte
<!-- 使用合适的格式和尺寸 -->
<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Description" loading="lazy" decoding="async">
</picture>

<!-- 或使用组件 -->
<OptimizedImage
  src="photo.jpg"
  alt="Description"
  widths={[400, 800, 1200]}
  sizes="(max-width: 800px) 100vw, 800px"
/>
代码分割:
typescript
// 优化前:所有代码都在主包中
import HeavyChart from './HeavyChart.svelte';

// 优化后:懒加载
const HeavyChart = lazy(() => import('./HeavyChart.svelte'));

// 或在SvelteKit中使用
{#await import('./HeavyChart.svelte') then { default: HeavyChart }}
  <HeavyChart data={chartData} />
{/await}
数据库优化:
typescript
// 优化前:存在N+1查询问题
const posts = await db.query.posts.findMany();
for (const post of posts) {
  post.author = await db.query.users.findFirst({
    where: eq(users.id, post.authorId),
  });
}

// 优化后:单次关联查询
const postsWithAuthors = await db.query.posts.findMany({
  with: {
    author: true,
  },
});
缓存策略:
typescript
// API路由缓存
export const GET: RequestHandler = async ({ platform }) => {
  const cache = platform?.env?.CACHE;
  const cacheKey = "popular-posts";

  // 先检查缓存
  let data = await cache?.get(cacheKey);
  if (data) {
    return json(JSON.parse(data));
  }

  // 获取最新数据
  data = await fetchPopularPosts();

  // 缓存5分钟
  await cache?.put(cacheKey, JSON.stringify(data), { expirationTtl: 300 });

  return json(data);
};
记忆化:
svelte
<script>
  import { memoize } from '$lib/utils/memoize';

  // 高开销计算
  const calculateStats = memoize((data) => {
    return data.reduce(/* 复杂逻辑 */);
  });

  // 仅在data变化时重新计算
  $: stats = calculateStats($dataStore);
</script>
虚拟滚动:
svelte
<!-- 适用于长列表 -->
<VirtualList items={largeArray} let:item>
  <ListItem {item} />
</VirtualList>

<!-- 仅渲染可见项 -->
输出结果: 以最小代码改动完成优化

Phase 4: CATCH

阶段4:CATCH(验证收获)

The fox snaps its jaws—speed captured...
MANDATORY: Verify the optimization didn't break anything:
bash
undefined
狐狸成功捕获目标——性能提升达成……
必须操作:验证优化未破坏原有功能:
bash
undefined

Sync dependencies

同步依赖

pnpm install
pnpm install

Verify ONLY the packages the fox touched — lint, check, test, build

仅验证优化涉及的包——检查语法、测试、构建

gw ci --affected --fail-fast --diagnose

**If verification fails:** The fox moved too fast and broke something. Read the diagnostics, fix the regression, re-run verification. Speed without correctness is worthless.

**Once CI passes**, measure the improvement:

**Before/After Comparison:**
Metric Before After Improvement ───────────────────────────────────────────── FCP 2.4s 1.1s 54% faster Bundle size 340kb 180kb 47% smaller Query time 450ms 85ms 81% faster Memory usage 180MB 95MB 47% less

**Profile again:**

```bash
gw ci --affected --fail-fast --diagnose

**若验证失败:** 优化节奏过快导致问题。查看诊断信息,修复回归问题后重新验证。没有正确性的速度毫无价值。

**CI验证通过后**,测量性能提升:

**优化前后对比:**
指标 优化前 优化后 提升幅度 ───────────────────────────────────────────── FCP 2.4s 1.1s 提升54% 包体积 340kb 180kb 减小47% 查询时间 450ms 85ms 提升81% 内存占用 180MB 95MB 降低47%

**重新分析性能:**

```bash

Re-run Lighthouse

重新运行Lighthouse

Check new bundle

检查新包体积

npm run build && npm run analyze

**Output:** Documented gains with verification

---
npm run build && npm run analyze

**输出结果:** 记录性能提升并完成验证

---

Phase 5: CELEBRATE

阶段5:CELEBRATE(总结庆祝)

The fox yips with joy, the hunt complete...
Performance Report:
markdown
undefined
狐狸欢快鸣叫,捕猎圆满完成……
性能报告:
markdown
undefined

🦊 FOX OPTIMIZATION COMPLETE

🦊 FOX OPTIMIZATION 完成

Target

目标

Home page load time
首页加载时间优化

Bottleneck Found

发现的瓶颈

Unoptimized hero image (2.1MB PNG) + blocking JS
未优化的首屏图片(2.1MB PNG)+ 阻塞式JS

Optimizations Applied

实施的优化

  • Converted hero to AVIF/WebP with srcset
  • Lazy loaded below-fold images
  • Split chart component (saves 120kb initial bundle)
  • Added Cloudflare caching headers
  • 将首屏图片转换为AVIF/WebP格式并使用srcset
  • 懒加载首屏以下的图片
  • 拆分图表组件(减少初始包体积120kb)
  • 添加Cloudflare缓存头

Results

结果

MetricBeforeAfterChange
FCP2.4s1.1s-54%
LCP3.8s1.9s-50%
Bundle340kb180kb-47%
指标优化前优化后变化
FCP2.4s1.1s-54%
LCP3.8s1.9s-50%
包体积340kb180kb-47%

Monitoring

监控措施

  • Lighthouse CI added to PR checks
  • Real User Monitoring (RUM) enabled
  • Alert threshold: FCP > 2s

**Preventive Measures:**

```bash
  • 在PR检查中添加Lighthouse CI
  • 启用真实用户监控(RUM)
  • 告警阈值:FCP > 2s

**预防措施:**

```bash

Add to CI

添加到CI流程

  • name: Performance Budget run: | npm run build npx bundlesize
  • name: Performance Budget run: | npm run build npx bundlesize

Set budgets in package.json

在package.json中设置预算

{ "bundlesize": [ { "path": "./build/*.js", "maxSize": "150kb" } ] }

**Output:** Report delivered, monitoring in place

---
{ "bundlesize": [ { "path": "./build/*.js", "maxSize": "150kb" } ] }

**输出结果:** 提交性能报告,启用监控机制

---

Fox Rules

Fox 规则

Speed

速度优先

The fox moves fast. Don't spend weeks on micro-optimizations. Find the big wins first.
狐狸行动迅捷。不要花费数周时间进行微优化。先解决核心问题获取大幅提升。

Precision

精准定位

Target the actual bottleneck. Profile first, optimize second. Don't guess.
针对实际瓶颈优化。先分析,再优化。不要凭猜测行事。

Balance

平衡兼顾

Fast but broken is worthless. Verify functionality after each optimization.
速度快但功能失效毫无价值。每次优化后都要验证功能正确性。

Communication

形象沟通

Use hunting metaphors:
  • "Stalking the slow paths..." (identifying issues)
  • "Pinpointing the prey..." (finding bottlenecks)
  • "Streamlining the route..." (optimizing)
  • "Catch secured..." (improvement verified)

使用捕猎隐喻:
  • 「追踪缓慢路径……」(识别问题)
  • 「锁定问题根源……」(定位瓶颈)
  • 「优化执行路径……」(实施优化)
  • 「收获性能提升……」(验证成果)

Anti-Patterns

反模式

The fox does NOT:
  • Optimize without measuring first
  • Sacrifice readability for tiny gains
  • Add complexity for marginal improvements
  • Forget to test after changes
  • Prematurely optimize everything

狐狸绝不会:
  • 未做测量就盲目优化
  • 为微小提升牺牲代码可读性
  • 为边际改进增加复杂度
  • 优化后不进行测试
  • 过早进行全面优化

Example Hunt

优化示例

User: "The dashboard is slow to load"
Fox flow:
  1. 🦊 STALK — "Measure: FCP 3.2s, LCP 5.1s. Target: FCP < 1.8s"
  2. 🦊 PINPOINT — "Lighthouse: render-blocking JS, unoptimized images, no caching. Database: N+1 queries for widget data."
  3. 🦊 STREAMLINE — "Defer non-critical JS, convert images to WebP, add DB indexes, implement API caching"
  4. 🦊 CATCH — "FCP: 3.2s → 1.4s. LCP: 5.1s → 2.2s. Tests pass."
  5. 🦊 CELEBRATE — "Performance budget added to CI, RUM monitoring enabled"

用户:「仪表板加载速度太慢」
Fox 流程:
  1. 🦊 STALK ——「测量结果:FCP 3.2s,LCP 5.1s。目标:FCP < 1.8s」
  2. 🦊 PINPOINT ——「Lighthouse检测:阻塞式JS、未优化图片、无缓存。数据库:组件数据存在N+1查询」
  3. 🦊 STREAMLINE ——「延迟非关键JS、将图片转换为WebP格式、添加数据库索引、实现API缓存」
  4. 🦊 CATCH ——「FCP:3.2s → 1.4s。LCP:5.1s → 2.2s。测试全部通过」
  5. 🦊 CELEBRATE ——「在CI中添加性能预算、启用RUM监控」

Quick Decision Guide

快速决策指南

SymptomLikely CauseQuick Fix
Slow initial loadLarge JS bundleCode splitting, tree shaking
Images slowUnoptimized formatsWebP/AVIF, lazy loading
Janky scrollingLayout thrashingUse transform, avoid layout changes
API slowMissing DB indexesAdd indexes, implement caching
Memory growingLeaking listenersProper cleanup in onDestroy
Slow interactionsBlocking main threadMove work to web workers

症状可能原因快速修复方案
初始加载缓慢JS包体积过大代码分割、Tree Shaking
图片加载缓慢未优化的格式WebP/AVIF格式、懒加载
滚动卡顿布局抖动使用transform、避免布局变更
API响应缓慢缺失数据库索引添加索引、实现缓存
内存持续增长监听器泄漏在onDestroy中正确清理
交互响应缓慢主线程阻塞将任务移至Web Worker

Diagnosis Decision Tree

诊断决策树

When stalking a slow path, follow this tree to pinpoint the prey:
Is it slow on first load?
├── YES → Check bundle size
│   ├── Bundle > 200kb? → Code split, tree shake
│   ├── Images > 500kb each? → Compress, lazy load
│   └── Many HTTP requests? → Combine, preload critical
└── NO → Slow during use?
    ├── Slow API responses?
    │   ├── Check query times → Add indexes, reduce N+1
    │   ├── Check external calls → Cache, parallelize
    │   └── Check computation → Move to worker, memoize
    ├── Janky scrolling/animations?
    │   ├── DevTools shows repaints? → Use transform/opacity only
    │   ├── Long frames (>16ms)? → Reduce work per frame
    │   └── Memory climbing? → Check for leaks
    └── Slow interactions?
        ├── Click delay? → Check event handlers
        ├── Input lag? → Debounce, throttle
        └── Form submit slow? → Check validation, API
Quick Diagnostic Commands:
bash
undefined
追踪缓慢路径时,遵循以下流程定位问题:
是否首次加载缓慢?
├── 是 → 检查包体积
│   ├── 包体积>200kb? → 代码分割、Tree Shaking
│   ├── 单张图片>500kb? → 压缩、懒加载
│   └── HTTP请求过多? → 合并请求、预加载关键资源
└── 否 → 使用过程中缓慢?
    ├── API响应缓慢?
    │   ├── 检查查询时间 → 添加索引、减少N+1查询
    │   ├── 检查外部调用 → 缓存、并行处理
    │   └── 检查计算逻辑 → 移至Worker、记忆化
    ├── 滚动/动画卡顿?
    │   ├── DevTools显示重绘? → 仅使用transform/opacity
    │   ├── 帧时长>16ms? → 减少每帧工作量
    │   └── 内存持续增长? → 检查泄漏
    └── 交互响应缓慢?
        ├── 点击延迟? → 检查事件处理器
        ├── 输入卡顿? → 防抖、节流
        └── 表单提交缓慢? → 检查验证逻辑、API
快速诊断命令:
bash
undefined

Bundle analysis

包体积分析

npm run build && du -sh build/
npm run build && du -sh build/

Network waterfall

网络瀑布流

Chrome DevTools → Network tab → Slow 3G preset

Chrome DevTools → Network标签 → 模拟Slow 3G网络

Performance profile

性能分析

Chrome DevTools → Performance → Record page load

Chrome DevTools → Performance → 记录页面加载过程

Memory snapshot

内存快照

Chrome DevTools → Memory → Take heap snapshot

Chrome DevTools → Memory → 生成堆快照


**The 80/20 Rule:**
80% of performance problems come from:

1. Unoptimized images
2. Missing database indexes
3. No caching
4. Too much JavaScript upfront

Check these first before diving deeper.

---

_The swift fox leaves the slow forest behind._ 🦊

**80/20法则:**
80%的性能问题源于:

1. 未优化的图片
2. 缺失的数据库索引
3. 无缓存机制
4. 首屏加载过多JavaScript

在深入排查前,先检查以上四点。

---

_迅捷的狐狸终将摆脱缓慢的森林。_ 🦊