[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79DDP5G29V84DWGDH2VRFXS":3,"skill-same:01M79DDP5G29V84DWGDH2VRFXS":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M79DDP5G29V84DWGDH2VRFXS","performance-optimization",null,"Optimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.","Zwin-ux\u002Fkit","Zwin-ux","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F64337759?v=4","01M79DBM821SD1S27FGNME1DVF","No Image","01M79DBM8N9HE5QF0YRHPMJPAJ",0,"MIT","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fperformance-optimization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: performance-optimization\ndescription: Optimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.\n---\n\n# Performance Optimization\n\n## Overview\n\nMeasure before optimizing. Performance work without measurement is guessing — and guessing leads to premature optimization that adds complexity without improving what matters. Profile first, identify the actual bottleneck, fix it, measure again. Optimize only what measurements prove matters.\n\n## When to Use\n\n- Performance requirements exist in the spec (load time budgets, response time SLAs)\n- Users or monitoring report slow behavior\n- Core Web Vitals scores are below thresholds\n- You suspect a change introduced a regression\n- Building features that handle large datasets or high traffic\n\n**When NOT to use:** Don't optimize before you have evidence of a problem. Premature optimization adds complexity that costs more than the performance it gains.\n\n## Core Web Vitals Targets\n\n| Metric | Good | Needs Improvement | Poor |\n|--------|------|-------------------|------|\n| **LCP** (Largest Contentful Paint) | ≤ 2.5s | ≤ 4.0s | > 4.0s |\n| **INP** (Interaction to Next Paint) | ≤ 200ms | ≤ 500ms | > 500ms |\n| **CLS** (Cumulative Layout Shift) | ≤ 0.1 | ≤ 0.25 | > 0.25 |\n\n## The Optimization Workflow\n\n```\n1. MEASURE  → Establish baseline with real data\n2. IDENTIFY → Find the actual bottleneck (not assumed)\n3. FIX      → Address the specific bottleneck\n4. VERIFY   → Measure again; keep or revert\n5. GUARD    → Add monitoring or tests to prevent regression\n```\n\n### Step 1: Measure\n\nTwo complementary approaches — use both:\n\n- **Synthetic (Lighthouse, DevTools Performance tab):** Controlled conditions, reproducible. Best for CI regression detection and isolating specific issues.\n- **RUM (web-vitals library, CrUX):** Real user data in real conditions. Required to validate that a fix actually improved user experience.\n\n**Frontend:**\n```bash\n# Synthetic: Lighthouse in Chrome DevTools (or CI)\n# Chrome DevTools → Performance tab → Record\n# Chrome DevTools MCP → Performance trace\n\n# RUM: Web Vitals library in code\nimport { onLCP, onINP, onCLS } from 'web-vitals';\n\nonLCP(console.log);\nonINP(console.log);\nonCLS(console.log);\n```\n\n**Backend:**\n```bash\n# Response time logging\n# Application Performance Monitoring (APM)\n# Database query logging with timing\n\n# Simple timing\nconsole.time('db-query');\nconst result = await db.query(...);\nconsole.timeEnd('db-query');\n```\n\n### Where to Start Measuring\n\nUse the symptom to decide what to measure first:\n\n```\nWhat is slow?\n├── First page load\n│   ├── Large bundle? --> Measure bundle size, check code splitting\n│   ├── Slow server response? --> Measure TTFB in DevTools Network waterfall\n│   │   ├── DNS long? --> Add dns-prefetch \u002F preconnect for known origins\n│   │   ├── TCP\u002FTLS long? --> Enable HTTP\u002F2, check edge deployment, keep-alive\n│   │   └── Waiting (server) long? --> Profile backend, check queries and caching\n│   └── Render-blocking resources? --> Check network waterfall for CSS\u002FJS blocking\n├── Interaction feels sluggish\n│   ├── UI freezes on click? --> Profile main thread, look for long tasks (>50ms)\n│   ├── Form input lag? --> Check re-renders, controlled component overhead\n│   └── Animation jank? --> Check layout thrashing, forced reflows\n├── Page after navigation\n│   ├── Data loading? --> Measure API response times, check for waterfalls\n│   └── Client rendering? --> Profile component render time, check for N+1 fetches\n└── Backend \u002F API\n    ├── Single endpoint slow? --> Profile database queries, check indexes\n    ├── All endpoints slow? --> Check connection pool, memory, CPU\n    └── Intermittent slowness? --> Check for lock contention, GC pauses, external deps\n```\n\n### Step 2: Identify the Bottleneck\n\nCommon bottlenecks by category:\n\n**Frontend:**\n\n| Symptom | Likely Cause | Investigation |\n|---------|-------------|---------------|\n| Slow LCP | Large images, render-blocking resources, slow server | Check network waterfall, image sizes |\n| High CLS | Images without dimensions, late-loading content, font shifts | Check layout shift attribution |\n| Poor INP | Heavy JavaScript on main thread, large DOM updates | Check long tasks in Performance trace |\n| Slow initial load | Large bundle, many network requests | Check bundle size, code splitting |\n\n**Backend:**\n\n| Symptom | Likely Cause | Investigation |\n|---------|-------------|---------------|\n| Slow API responses | N+1 queries, missing indexes, unoptimized queries | Check database query log |\n| Memory growth | Leaked references, unbounded caches, large payloads | Heap snapshot analysis |\n| CPU spikes | Synchronous heavy computation, regex backtracking | CPU profiling |\n| High latency | Missing caching, redundant computation, network hops | Trace requests through the stack |\n\n### Step 3: Fix Common Anti-Patterns\n\n#### N+1 Queries (Backend)\n\n```typescript\n\u002F\u002F BAD: N+1 — one query per task for the owner\nconst tasks = await db.tasks.findMany();\nfor (const task of tasks) {\n  task.owner = await db.users.findUnique({ where: { id: task.ownerId } });\n}\n\n\u002F\u002F GOOD: Single query with join\u002Finclude\nconst tasks = await db.tasks.findMany({\n  include: { owner: true },\n});\n```\n\n#### Unbounded Data Fetching\n\n```typescript\n\u002F\u002F BAD: Fetching all records\nconst allTasks = await db.tasks.findMany();\n\n\u002F\u002F GOOD: Paginated with limits\nconst tasks = await db.tasks.findMany({\n  take: 20,\n  skip: (page - 1) * 20,\n  orderBy: { createdAt: 'desc' },\n});\n```\n\n#### Missing Image Optimization (Frontend)\n\n```html\n\u003C!-- BAD: No dimensions, no format optimization -->\n\u003Cimg src=\"\u002Fhero.jpg\" \u002F>\n\n\u003C!-- GOOD: Hero \u002F LCP image — art direction + resolution switching, high priority -->\n\u003C!--\n  Two techniques combined:\n  - Art direction (media): different crop\u002Fcomposition per breakpoint\n  - Resolution switching (srcset + sizes): right file size per screen density\n-->\n\u003Cpicture>\n  \u003C!-- Mobile: portrait crop (8:10) -->\n  \u003Csource\n    media=\"(max-width: 767px)\"\n    srcset=\"\u002Fhero-mobile-400.avif 400w, \u002Fhero-mobile-800.avif 800w\"\n    sizes=\"100vw\"\n    width=\"800\"\n    height=\"1000\"\n    type=\"image\u002Favif\"\n  \u002F>\n  \u003Csource\n    media=\"(max-width: 767px)\"\n    srcset=\"\u002Fhero-mobile-400.webp 400w, \u002Fhero-mobile-800.webp 800w\"\n    sizes=\"100vw\"\n    width=\"800\"\n    height=\"1000\"\n    type=\"image\u002Fwebp\"\n  \u002F>\n  \u003C!-- Desktop: landscape crop (2:1) -->\n  \u003Csource\n    srcset=\"\u002Fhero-800.avif 800w, \u002Fhero-1200.avif 1200w, \u002Fhero-1600.avif 1600w\"\n    sizes=\"(max-width: 1200px) 100vw, 1200px\"\n    width=\"1200\"\n    height=\"600\"\n    type=\"image\u002Favif\"\n  \u002F>\n  \u003Csource\n    srcset=\"\u002Fhero-800.webp 800w, \u002Fhero-1200.webp 1200w, \u002Fhero-1600.webp 1600w\"\n    sizes=\"(max-width: 1200px) 100vw, 1200px\"\n    width=\"1200\"\n    height=\"600\"\n    type=\"image\u002Fwebp\"\n  \u002F>\n  \u003Cimg\n    src=\"\u002Fhero-desktop.jpg\"\n    width=\"1200\"\n    height=\"600\"\n    fetchpriority=\"high\"\n    alt=\"Hero image description\"\n  \u002F>\n\u003C\u002Fpicture>\n\n\u003C!-- GOOD: Below-the-fold image — lazy loaded + async decoding -->\n\u003Cimg\n  src=\"\u002Fcontent.webp\"\n  width=\"800\"\n  height=\"400\"\n  loading=\"lazy\"\n  decoding=\"async\"\n  alt=\"Content image description\"\n\u002F>\n```\n\n#### Unnecessary Re-renders (React)\n\n```tsx\n\u002F\u002F BAD: Creates new object on every render, causing children to re-render\nfunction TaskList() {\n  return \u003CTaskFilters options={{ sortBy: 'date', order: 'desc' }} \u002F>;\n}\n\n\u002F\u002F GOOD: Stable reference\nconst DEFAULT_OPTIONS = { sortBy: 'date', order: 'desc' } as const;\nfunction TaskList() {\n  return \u003CTaskFilters options={DEFAULT_OPTIONS} \u002F>;\n}\n\n\u002F\u002F Use React.memo for expensive components\nconst TaskItem = React.memo(function TaskItem({ task }: Props) {\n  return \u003Cdiv>{\u002F* expensive render *\u002F}\u003C\u002Fdiv>;\n});\n\n\u002F\u002F Use useMemo for expensive computations\nfunction TaskStats({ tasks }: Props) {\n  const stats = useMemo(() => calculateStats(tasks), [tasks]);\n  return \u003Cdiv>{stats.completed} \u002F {stats.total}\u003C\u002Fdiv>;\n}\n```\n\n#### Large Bundle Size\n\n```typescript\n\u002F\u002F Modern bundlers (Vite, webpack 5+) handle named imports with tree-shaking automatically,\n\u002F\u002F provided the dependency ships ESM and is marked `sideEffects: false` in package.json.\n\u002F\u002F Profile before changing import styles — the real gains come from splitting and lazy loading.\n\n\u002F\u002F GOOD: Dynamic import for heavy, rarely-used features\nconst ChartLibrary = lazy(() => import('.\u002FChartLibrary'));\n\n\u002F\u002F GOOD: Route-level code splitting wrapped in Suspense\nconst SettingsPage = lazy(() => import('.\u002Fpages\u002FSettings'));\n\nfunction App() {\n  return (\n    \u003CSuspense fallback={\u003CSpinner \u002F>}>\n      \u003CSettingsPage \u002F>\n    \u003C\u002FSuspense>\n  );\n}\n```\n\n#### Missing Caching (Backend)\n\n```typescript\n\u002F\u002F Cache frequently-read, rarely-changed data\nconst CACHE_TTL = 5 * 60 * 1000; \u002F\u002F 5 minutes\nlet cachedConfig: AppConfig | null = null;\nlet cacheExpiry = 0;\n\nasync function getAppConfig(): Promise\u003CAppConfig> {\n  if (cachedConfig && Date.now() \u003C cacheExpiry) {\n    return cachedConfig;\n  }\n  cachedConfig = await db.config.findFirst();\n  cacheExpiry = Date.now() + CACHE_TTL;\n  return cachedConfig;\n}\n\n\u002F\u002F HTTP caching headers for static assets\napp.use('\u002Fstatic', express.static('public', {\n  maxAge: '1y',           \u002F\u002F Cache for 1 year\n  immutable: true,        \u002F\u002F Never revalidate (use content hashing in filenames)\n}));\n\n\u002F\u002F Cache-Control for API responses\nres.set('Cache-Control', 'public, max-age=300'); \u002F\u002F 5 minutes\n```\n\n### Step 4: Verify (Keep or Revert)\n\nA fix is a hypothesis until you re-measure. This step decides whether it survives.\n\n**Re-measure the way you measured the baseline:** same command, same conditions, same fixed budget (wall-clock, sample count, or request count). A baseline taken on a cold cache against a result taken on a warm one measures the cache, not your change.\n\n**Change one thing at a time.** Three optimizations landed together produce one number, and you cannot attribute it. If they must ship together, measure each in isolation first.\n\n**Beat the noise, not just the mean.** Repeat the measurement and compare the delta against run-to-run variance. A 3% gain inside ±5% variance is not a gain; it is a different sample.\n\nThen decide, strictly:\n\n| Result vs. baseline | Action |\n|---|---|\n| Past the threshold, tests green | **Keep.** Commit with the before\u002Fafter numbers in the message. |\n| Within noise (no measurable change) | **Revert.** |\n| Worse | **Revert.** |\n| Improved, but a test went red | **Revert.** A regression wearing a win's clothing. |\n\n**\"Neutral\" is a revert, not a keep.** This is the step teams skip: the change is already written, throwing it away feels wasteful, so it lands unmeasured, and the codebase accretes complexity that never bought anything. Code you keep, you maintain forever. Make it pay for itself.\n\n**Correctness gates the metric.** The suite stays green *and* the number moves. An \"optimization\" that wins by dropping work the product needed (skipping a validation, caching something that must be fresh, removing an `await` that was load-bearing) is a regression, not a win.\n\n#### Log every attempt, including the reverted ones\n\nReverted work leaves no trace in git history, which is exactly why the same dead idea gets tried again next quarter. Keep a short ledger so a discarded idea stays discarded:\n\n| Idea | Baseline → Result | Verdict | Why |\n|---|---|---|---|\n| Memoize the row component | INP 240ms → 235ms | reverted | Inside noise (±15ms). Rows weren't the bottleneck. |\n| Virtualize the list | INP 240ms → 90ms | kept | Long tasks gone from the trace. |\n| Preconnect to the API origin | LCP 2.8s → 2.8s | reverted | Already same-origin. |\n\nA section in the PR description or a `PERF.md` in the repo both work. What matters is that the next person (or the next agent) reads it before proposing an experiment, and doesn't re-run one that already failed.\n\n## Performance Budget\n\nSet budgets and enforce them:\n\n```\nJavaScript bundle: \u003C 200KB gzipped (initial load)\nCSS: \u003C 50KB gzipped\nImages: \u003C 200KB per image (above the fold)\nFonts: \u003C 100KB total\nAPI response time: \u003C 200ms (p95)\nTime to Interactive: \u003C 3.5s on 4G\nLighthouse Performance score: ≥ 90\n```\n\n**Enforce in CI:**\n```bash\n# Bundle size check\nnpx bundlesize --config bundlesize.config.json\n\n# Lighthouse CI\nnpx lhci autorun\n```\n\n## See Also\n\nFor detailed performance checklists, optimization commands, and anti-pattern reference, see `references\u002Fperformance-checklist.md`.\n\n\n## Common Rationalizations\n\n| Rationalization | Reality |\n|---|---|\n| \"We'll optimize later\" | Performance debt compounds. Fix obvious anti-patterns now, defer micro-optimizations. |\n| \"It's fast on my machine\" | Your machine isn't the user's. Profile on representative hardware and networks. |\n| \"This optimization is obvious\" | If you didn't measure, you don't know. Profile first. |\n| \"Users won't notice 100ms\" | Research shows 100ms delays impact conversion rates. Users notice more than you think. |\n| \"The framework handles performance\" | Frameworks prevent some issues but can't fix N+1 queries or oversized bundles. |\n| \"It didn't help much, but it doesn't hurt\" | Neutral changes are a revert. You pay maintenance on them forever and got nothing back. |\n| \"We already wrote it, may as well keep it\" | Sunk cost. The measurement doesn't care how long the change took to write. |\n| \"The improvement is obvious, no need to re-measure\" | Then re-measuring is cheap and proves it. Unmeasured wins are how neutral complexity lands. |\n\n## Red Flags\n\n- Optimization without profiling data to justify it\n- N+1 query patterns in data fetching\n- List endpoints without pagination\n- Images without dimensions, lazy loading, or responsive sizes\n- Bundle size growing without review\n- No performance monitoring in production\n- `React.memo` and `useMemo` everywhere (overusing is as bad as underusing)\n- Optimizations kept without a re-measurement that justifies them\n- Several optimizations bundled into one measurement, so no single change can be attributed\n- A \"win\" that required a test to be changed, skipped, or deleted\n- The same failed optimization attempted more than once because nobody recorded the first attempt\n\n## Verification\n\nAfter any performance-related change:\n\n- [ ] Before and after measurements exist (specific numbers)\n- [ ] The result was re-measured the same way as the baseline (same command, same conditions)\n- [ ] The improvement exceeds run-to-run variance, not just the mean\n- [ ] Changes that didn't beat the baseline were reverted, not kept as neutral\n- [ ] Attempts are logged, kept and reverted alike, so a dead idea isn't re-run\n- [ ] The specific bottleneck is identified and addressed\n- [ ] Core Web Vitals are within \"Good\" thresholds\n- [ ] Bundle size hasn't increased significantly\n- [ ] No N+1 queries in new data fetching code\n- [ ] Performance budget passes in CI (if configured)\n- [ ] Existing tests still pass (optimization didn't break behavior)\n","# Performance Optimization\n\n## Overview\n\nMeasure before optimizing. Performance work without measurement is guessing — and guessing leads to premature optimization that adds complexity without improving what matters. Profile first, identify the actual bottleneck, fix it, measure again. Optimize only what measurements prove matters.\n\n## When to Use\n\n- Performance requirements exist in the spec (load time budgets, response time SLAs)\n- Users or monitoring report slow behavior\n- Core Web Vitals scores are below thresholds\n- You suspect a change introduced a regression\n- Building features that handle large datasets or high traffic\n\n**When NOT to use:** Don't optimize before you have evidence of a problem. Premature optimization adds complexity that costs more than the performance it gains.\n\n## Core Web Vitals Targets\n\n| Metric | Good | Needs Improvement | Poor |\n|--------|------|-------------------|------|\n| **LCP** (Largest Contentful Paint) | ≤ 2.5s | ≤ 4.0s | > 4.0s |\n| **INP** (Interaction to Next Paint) | ≤ 200ms | ≤ 500ms | > 500ms |\n| **CLS** (Cumulative Layout Shift) | ≤ 0.1 | ≤ 0.25 | > 0.25 |\n\n## The Optimization Workflow\n\n```\n1. MEASURE  → Establish baseline with real data\n2. IDENTIFY → Find the actual bottleneck (not assumed)\n3. FIX      → Address the specific bottleneck\n4. VERIFY   → Measure again; keep or revert\n5. GUARD    → Add monitoring or tests to prevent regression\n```\n\n### Step 1: Measure\n\nTwo complementary approaches — use both:\n\n- **Synthetic (Lighthouse, DevTools Performance tab):** Controlled conditions, reproducible. Best for CI regression detection and isolating specific issues.\n- **RUM (web-vitals library, CrUX):** Real user data in real conditions. Required to validate that a fix actually improved user experience.\n\n**Frontend:**\n```bash\n# Synthetic: Lighthouse in Chrome DevTools (or CI)\n# Chrome DevTools → Performance tab → Record\n# Chrome DevTools MCP → Performance trace\n\n# RUM: Web Vitals library in code\nimport { onLCP, onINP, onCLS } from 'web-vitals';\n\nonLCP(console.log);\nonINP(console.log);\nonCLS(console.log);\n```\n\n**Backend:**\n```bash\n# Response time logging\n# Application Performance Monitoring (APM)\n# Database query logging with timing\n\n# Simple timing\nconsole.time('db-query');\nconst result = await db.query(...);\nconsole.timeEnd('db-query');\n```\n\n### Where to Start Measuring\n\nUse the symptom to decide what to measure first:\n\n```\nWhat is slow?\n├── First page load\n│   ├── Large bundle? --> Measure bundle size, check code splitting\n│   ├── Slow server response? --> Measure TTFB in DevTools Network waterfall\n│   │   ├── DNS long? --> Add dns-prefetch \u002F preconnect for known origins\n│   │   ├── TCP\u002FTLS long? --> Enable HTTP\u002F2, check edge deployment, keep-alive\n│   │   └── Waiting (server) long? --> Profile backend, check queries and caching\n│   └── Render-blocking resources? --> Check network waterfall for CSS\u002FJS blocking\n├── Interaction feels sluggish\n│   ├── UI freezes on click? --> Profile main thread, look for long tasks (>50ms)\n│   ├── Form input lag? --> Check re-renders, controlled component overhead\n│   └── Animation jank? --> Check layout thrashing, forced reflows\n├── Page after navigation\n│   ├── Data loading? --> Measure API response times, check for waterfalls\n│   └── Client rendering? --> Profile component render time, check for N+1 fetches\n└── Backend \u002F API\n    ├── Single endpoint slow? --> Profile database queries, check indexes\n    ├── All endpoints slow? --> Check connection pool, memory, CPU\n    └── Intermittent slowness? --> Check for lock contention, GC pauses, external deps\n```\n\n### Step 2: Identify the Bottleneck\n\nCommon bottlenecks by category:\n\n**Frontend:**\n\n| Symptom | Likely Cause | Investigation |\n|---------|-------------|---------------|\n| Slow LCP | Large images, render-blocking resources, slow server | Check network waterfall, image sizes |\n| High CLS | Images without dimensions, late-loading content, font shifts | Check layout shift attribution |\n| Poor INP | Heavy JavaScript on main thread, large DOM updates | Check long tasks in Performance trace |\n| Slow initial load | Large bundle, many network requests | Check bundle size, code splitting |\n\n**Backend:**\n\n| Symptom | Likely Cause | Investigation |\n|---------|-------------|---------------|\n| Slow API responses | N+1 queries, missing indexes, unoptimized queries | Check database query log |\n| Memory growth | Leaked references, unbounded caches, large payloads | Heap snapshot analysis |\n| CPU spikes | Synchronous heavy computation, regex backtracking | CPU profiling |\n| High latency | Missing caching, redundant computation, network hops | Trace requests through the stack |\n\n### Step 3: Fix Common Anti-Patterns\n\n#### N+1 Queries (Backend)\n\n```typescript\n\u002F\u002F BAD: N+1 — one query per task for the owner\nconst tasks = await db.tasks.findMany();\nfor (const task of tasks) {\n  task.owner = await db.users.findUnique({ where: { id: task.ownerId } });\n}\n\n\u002F\u002F GOOD: Single query with join\u002Finclude\nconst tasks = await db.tasks.findMany({\n  include: { owner: true },\n});\n```\n\n#### Unbounded Data Fetching\n\n```typescript\n\u002F\u002F BAD: Fetching all records\nconst allTasks = await db.tasks.findMany();\n\n\u002F\u002F GOOD: Paginated with limits\nconst tasks = await db.tasks.findMany({\n  take: 20,\n  skip: (page - 1) * 20,\n  orderBy: { createdAt: 'desc' },\n});\n```\n\n#### Missing Image Optimization (Frontend)\n\n```html\n\u003C!-- BAD: No dimensions, no format optimization -->\n\u003Cimg src=\"\u002Fhero.jpg\" \u002F>\n\n\u003C!-- GOOD: Hero \u002F LCP image — art direction + resolution switching, high priority -->\n\u003C!--\n  Two techniques combined:\n  - Art direction (media): different crop\u002Fcomposition per breakpoint\n  - Resolution switching (srcset + sizes): right file size per screen density\n-->\n\u003Cpicture>\n  \u003C!-- Mobile: portrait crop (8:10) -->\n  \u003Csource\n    media=\"(max-width: 767px)\"\n    srcset=\"\u002Fhero-mobile-400.avif 400w, \u002Fhero-mobile-800.avif 800w\"\n    sizes=\"100vw\"\n    width=\"800\"\n    height=\"1000\"\n    type=\"image\u002Favif\"\n  \u002F>\n  \u003Csource\n    media=\"(max-width: 767px)\"\n    srcset=\"\u002Fhero-mobile-400.webp 400w, \u002Fhero-mobile-800.webp 800w\"\n    sizes=\"100vw\"\n    width=\"800\"\n    height=\"1000\"\n    type=\"image\u002Fwebp\"\n  \u002F>\n  \u003C!-- Desktop: landscape crop (2:1) -->\n  \u003Csource\n    srcset=\"\u002Fhero-800.avif 800w, \u002Fhero-1200.avif 1200w, \u002Fhero-1600.avif 1600w\"\n    sizes=\"(max-width: 1200px) 100vw, 1200px\"\n    width=\"1200\"\n    height=\"600\"\n    type=\"image\u002Favif\"\n  \u002F>\n  \u003Csource\n    srcset=\"\u002Fhero-800.webp 800w, \u002Fhero-1200.webp 1200w, \u002Fhero-1600.webp 1600w\"\n    sizes=\"(max-width: 1200px) 100vw, 1200px\"\n    width=\"1200\"\n    height=\"600\"\n    type=\"image\u002Fwebp\"\n  \u002F>\n  \u003Cimg\n    src=\"\u002Fhero-desktop.jpg\"\n    width=\"1200\"\n    height=\"600\"\n    fetchpriority=\"high\"\n    alt=\"Hero image description\"\n  \u002F>\n\u003C\u002Fpicture>\n\n\u003C!-- GOOD: Below-the-fold image — lazy loaded + async decoding -->\n\u003Cimg\n  src=\"\u002Fcontent.webp\"\n  width=\"800\"\n  height=\"400\"\n  loading=\"lazy\"\n  decoding=\"async\"\n  alt=\"Content image description\"\n\u002F>\n```\n\n#### Unnecessary Re-renders (React)\n\n```tsx\n\u002F\u002F BAD: Creates new object on every render, causing children to re-render\nfunction TaskList() {\n  return \u003CTaskFilters options={{ sortBy: 'date', order: 'desc' }} \u002F>;\n}\n\n\u002F\u002F GOOD: Stable reference\nconst DEFAULT_OPTIONS = { sortBy: 'date', order: 'desc' } as const;\nfunction TaskList() {\n  return \u003CTaskFilters options={DEFAULT_OPTIONS} \u002F>;\n}\n\n\u002F\u002F Use React.memo for expensive components\nconst TaskItem = React.memo(function TaskItem({ task }: Props) {\n  return \u003Cdiv>{\u002F* expensive render *\u002F}\u003C\u002Fdiv>;\n});\n\n\u002F\u002F Use useMemo for expensive computations\nfunction TaskStats({ tasks }: Props) {\n  const stats = useMemo(() => calculateStats(tasks), [tasks]);\n  return \u003Cdiv>{stats.completed} \u002F {stats.total}\u003C\u002Fdiv>;\n}\n```\n\n#### Large Bundle Size\n\n```typescript\n\u002F\u002F Modern bundlers (Vite, webpack 5+) handle named imports with tree-shaking automatically,\n\u002F\u002F provided the dependency ships ESM and is marked `sideEffects: false` in package.json.\n\u002F\u002F Profile before changing import styles — the real gains come from splitting and lazy loading.\n\n\u002F\u002F GOOD: Dynamic import for heavy, rarely-used features\nconst ChartLibrary = lazy(() => import('.\u002FChartLibrary'));\n\n\u002F\u002F GOOD: Route-level code splitting wrapped in Suspense\nconst SettingsPage = lazy(() => import('.\u002Fpages\u002FSettings'));\n\nfunction App() {\n  return (\n    \u003CSuspense fallback={\u003CSpinner \u002F>}>\n      \u003CSettingsPage \u002F>\n    \u003C\u002FSuspense>\n  );\n}\n```\n\n#### Missing Caching (Backend)\n\n```typescript\n\u002F\u002F Cache frequently-read, rarely-changed data\nconst CACHE_TTL = 5 * 60 * 1000; \u002F\u002F 5 minutes\nlet cachedConfig: AppConfig | null = null;\nlet cacheExpiry = 0;\n\nasync function getAppConfig(): Promise\u003CAppConfig> {\n  if (cachedConfig && Date.now() \u003C cacheExpiry) {\n    return cachedConfig;\n  }\n  cachedConfig = await db.config.findFirst();\n  cacheExpiry = Date.now() + CACHE_TTL;\n  return cachedConfig;\n}\n\n\u002F\u002F HTTP caching headers for static assets\napp.use('\u002Fstatic', express.static('public', {\n  maxAge: '1y',           \u002F\u002F Cache for 1 year\n  immutable: true,        \u002F\u002F Never revalidate (use content hashing in filenames)\n}));\n\n\u002F\u002F Cache-Control for API responses\nres.set('Cache-Control', 'public, max-age=300'); \u002F\u002F 5 minutes\n```\n\n### Step 4: Verify (Keep or Revert)\n\nA fix is a hypothesis until you re-measure. This step decides whether it survives.\n\n**Re-measure the way you measured the baseline:** same command, same conditions, same fixed budget (wall-clock, sample count, or request count). A baseline taken on a cold cache against a result taken on a warm one measures the cache, not your change.\n\n**Change one thing at a time.** Three optimizations landed together produce one number, and you cannot attribute it. If they must ship together, measure each in isolation first.\n\n**Beat the noise, not just the mean.** Repeat the measurement and compare the delta against run-to-run variance. A 3% gain inside ±5% variance is not a gain; it is a different sample.\n\nThen decide, strictly:\n\n| Result vs. baseline | Action |\n|---|---|\n| Past the threshold, tests green | **Keep.** Commit with the before\u002Fafter numbers in the message. |\n| Within noise (no measurable change) | **Revert.** |\n| Worse | **Revert.** |\n| Improved, but a test went red | **Revert.** A regression wearing a win's clothing. |\n\n**\"Neutral\" is a revert, not a keep.** This is the step teams skip: the change is already written, throwing it away feels wasteful, so it lands unmeasured, and the codebase accretes complexity that never bought anything. Code you keep, you maintain forever. Make it pay for itself.\n\n**Correctness gates the metric.** The suite stays green *and* the number moves. An \"optimization\" that wins by dropping work the product needed (skipping a validation, caching something that must be fresh, removing an `await` that was load-bearing) is a regression, not a win.\n\n#### Log every attempt, including the reverted ones\n\nReverted work leaves no trace in git history, which is exactly why the same dead idea gets tried again next quarter. Keep a short ledger so a discarded idea stays discarded:\n\n| Idea | Baseline → Result | Verdict | Why |\n|---|---|---|---|\n| Memoize the row component | INP 240ms → 235ms | reverted | Inside noise (±15ms). Rows weren't the bottleneck. |\n| Virtualize the list | INP 240ms → 90ms | kept | Long tasks gone from the trace. |\n| Preconnect to the API origin | LCP 2.8s → 2.8s | reverted | Already same-origin. |\n\nA section in the PR description or a `PERF.md` in the repo both work. What matters is that the next person (or the next agent) reads it before proposing an experiment, and doesn't re-run one that already failed.\n\n## Performance Budget\n\nSet budgets and enforce them:\n\n```\nJavaScript bundle: \u003C 200KB gzipped (initial load)\nCSS: \u003C 50KB gzipped\nImages: \u003C 200KB per image (above the fold)\nFonts: \u003C 100KB total\nAPI response time: \u003C 200ms (p95)\nTime to Interactive: \u003C 3.5s on 4G\nLighthouse Performance score: ≥ 90\n```\n\n**Enforce in CI:**\n```bash\n# Bundle size check\nnpx bundlesize --config bundlesize.config.json\n\n# Lighthouse CI\nnpx lhci autorun\n```\n\n## See Also\n\nFor detailed performance checklists, optimization commands, and anti-pattern reference, see `references\u002Fperformance-checklist.md`.\n\n\n## Common Rationalizations\n\n| Rationalization | Reality |\n|---|---|\n| \"We'll optimize later\" | Performance debt compounds. Fix obvious anti-patterns now, defer micro-optimizations. |\n| \"It's fast on my machine\" | Your machine isn't the user's. Profile on representative hardware and networks. |\n| \"This optimization is obvious\" | If you didn't measure, you don't know. Profile first. |\n| \"Users won't notice 100ms\" | Research shows 100ms delays impact conversion rates. Users notice more than you think. |\n| \"The framework handles performance\" | Frameworks prevent some issues but can't fix N+1 queries or oversized bundles. |\n| \"It didn't help much, but it doesn't hurt\" | Neutral changes are a revert. You pay maintenance on them forever and got nothing back. |\n| \"We already wrote it, may as well keep it\" | Sunk cost. The measurement doesn't care how long the change took to write. |\n| \"The improvement is obvious, no need to re-measure\" | Then re-measuring is cheap and proves it. Unmeasured wins are how neutral complexity lands. |\n\n## Red Flags\n\n- Optimization without profiling data to justify it\n- N+1 query patterns in data fetching\n- List endpoints without pagination\n- Images without dimensions, lazy loading, or responsive sizes\n- Bundle size growing without review\n- No performance monitoring in production\n- `React.memo` and `useMemo` everywhere (overusing is as bad as underusing)\n- Optimizations kept without a re-measurement that justifies them\n- Several optimizations bundled into one measurement, so no single change can be attributed\n- A \"win\" that required a test to be changed, skipped, or deleted\n- The same failed optimization attempted more than once because nobody recorded the first attempt\n\n## Verification\n\nAfter any performance-related change:\n\n- [ ] Before and after measurements exist (specific numbers)\n- [ ] The result was re-measured the same way as the baseline (same command, same conditions)\n- [ ] The improvement exceeds run-to-run variance, not just the mean\n- [ ] Changes that didn't beat the baseline were reverted, not kept as neutral\n- [ ] Attempts are logged, kept and reverted alike, so a dead idea isn't re-run\n- [ ] The specific bottleneck is identified and addressed\n- [ ] Core Web Vitals are within \"Good\" thresholds\n- [ ] Bundle size hasn't increased significantly\n- [ ] No N+1 queries in new data fetching code\n- [ ] Performance budget passes in CI (if configured)\n- [ ] Existing tests still pass (optimization didn't break behavior)\n",{"name":5,"description":7},"main","247d14fbfd2c6f3266558d168266b02141477140",".agents\u002Fskills\u002Fperformance-optimization",2,"https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit","https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@mzwin\u002Fkit","https:\u002F\u002Fgithub.com\u002FZwin-ux","i like to code","2026-11-02 01:46:54",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Zwin-ux\u002Fkit --skill performance-optimization",{"tool":39,"command":40},"bunx","bunx skills add Zwin-ux\u002Fkit --skill performance-optimization",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Zwin-ux\u002Fkit --skill performance-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fperformance-optimization\u002FSKILL.md",true,[],[48,54,61,68,75,82],{"skillNo":49,"name":50,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M79DG9E74YF71H97VHA4E7FJ","concepts","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002Fwiki\u002Fkit-1.0\u002Fwiki\u002Fconcepts\u002FSkill.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M79DG83S8WTMRAH47T2D0WKE","write-tests","Add focused tests for important project behavior.","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002Fskills\u002Fwrite-tests\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M79DG60377KCK4Y83SQWAE66","workspace-setup","Set up monorepo and multi-package workspaces for agents and humans.","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002Fskills\u002Fworkspace-setup\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M79DG4N07X3KM7F89G7V4T4B","ship-checklist","Run a practical pre-ship checklist for an app release.","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002Fskills\u002Fship-checklist\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M79DG2PD1PZG9ZW1YF11X0C3","project-setup","Set up a clean project baseline for agents and humans.","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002Fskills\u002Fproject-setup\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M79DG17XXG8RTZF3YQA3JT2S","pr-ready","Prepare a clear pull request summary, test plan, and risk notes.","https:\u002F\u002Fgithub.com\u002FZwin-ux\u002Fkit\u002Fblob\u002Fmain\u002Fskills\u002Fpr-ready\u002FSKILL.md",[],[]]