[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79EF55G9K8J1VCWD8A1SW8X":3,"skill-same:01M79EF55G9K8J1VCWD8A1SW8X":48},{"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":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79EF55G9K8J1VCWD8A1SW8X","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.","hamzabellouch\u002Fagent-skills","hamzabellouch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F237856042?v=4","01M79BRYW7XAMK3YDWQEMTWGWS","Hamza Bellouch","01M79BRYWXQV3JK2TGVTX8GN2A",8,"MIT","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FSoftware_Engineering_Practices\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, confirm improvement\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## 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\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\n## Verification\n\nAfter any performance-related change:\n\n- [ ] Before and after measurements exist (specific numbers)\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, confirm improvement\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## 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\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\n## Verification\n\nAfter any performance-related change:\n\n- [ ] Before and after measurements exist (specific numbers)\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","e905af21e5f1e1c3ca605e9656c3a7930360a84e","Programming\u002FSoftware_Engineering_Practices\u002Fperformance-optimization",1,"https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills","https:\u002F\u002Fhamzabellouch.github.io\u002F","https:\u002F\u002Fgithub.com\u002Fhamzabellouch","hamzabellouch.github.io","CEO & Founder of @tknoglobal | Researcher in Technology & Applied Sciences.","2026-10-17 03:20:19",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add hamzabellouch\u002Fagent-skills --skill performance-optimization",{"tool":40,"command":41},"bunx","bunx skills add hamzabellouch\u002Fagent-skills --skill performance-optimization",{"tool":43,"command":44},"pnpm","pnpm dlx skills add hamzabellouch\u002Fagent-skills --skill performance-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FSoftware_Engineering_Practices\u002Fperformance-optimization\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M79FHH2H815A9TAP6WNKH4Q8","security-audit","Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FSecurity_Audit_and_Code_Review\u002Fsecurity-audit\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M79FHBGXVBY6VQ1X7ETAZMF1","malware-analysis-reversing","Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static\u002Fdynamic binary analysis, memory forensics, and YARA detection rule authoring.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fmalware-analysis-reversing\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79FH6EACDR801TZCE4R8SAC","application-security-pentesting","Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST\u002FDAST pipeline integration, secure code review, threat modeling, and defensive security posture.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fapplication-security-pentesting\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79FH0VKVT44FK923K520ZQA","oauth2-oidc-security-flows","Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Foauth2-oidc-security-flows\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79FGVVB3R4T88XXD8FRSV5B","jwt-session-management-hardening","Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256\u002FEdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Fjwt-session-management-hardening\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79FGNCPZ85CVEY0B3NE4H3B","soc2-compliance-automation","Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI\u002FCD security gates.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FGovernance_Compliance_and_Legal_Tech\u002Fsoc2-compliance-automation\u002FSKILL.md",[],[]]