[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6BVQND87R8RH9B7JCS4T1B9":3,"skill-same:01M6BVQND87R8RH9B7JCS4T1B9":102},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":55,"commitSha":56,"skillDirectory":57,"forksCount":58,"repositoryHtmlUrl":59,"repositoryHomepageUrl":17,"ownerHtmlUrl":60,"ownerBlogUrl":61,"ownerDescription":62,"updatedAt":63,"install":64,"resources":77},"01M6BVQND87R8RH9B7JCS4T1B9","performance-optimization","代码性能优化","This skill should be used when the user asks to \"optimize performance\", \"make this faster\", \"profile this code\", \"fix slow code\", \"reduce memory usage\", \"improve efficiency\", \"find bottlenecks\", or mentions performance issues, slow execution, or memory leaks.","当用户要求“优化性能”、“让代码更快”、“对代码进行性能剖析”、“修复缓慢代码”、“减少内存占用”、“提升效率”、“定位瓶颈”，或提到性能问题、执行缓慢、内存泄漏时应使用该技能。","feniix\u002Fdotfiles","feniix","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F91633?v=4","01M6BVMJ0Q5E6HZ4JTEWYBBKV9","Sebastian B Otaegui","01M6BVMJ53ZV8DFKXTRBPESTF3",8,"MIT",null,"https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fperformance-optimization\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C796JZ1YCTM2B2X7TKEWZZ","性能剖析与优化","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"performance","Optimization","performance optimization","when","memory","reduce","usage","make","efficiency","optimize","fix","profile","user","find","improve","execution","issues","code","2026-11-10 10:12:30",false,"---\nname: performance-optimization\ndescription: This skill should be used when the user asks to \"optimize performance\", \"make this faster\", \"profile this code\", \"fix slow code\", \"reduce memory usage\", \"improve efficiency\", \"find bottlenecks\", or mentions performance issues, slow execution, or memory leaks.\nversion: 2.0.0\n---\n\n> **Note:** This skill should NOT be used proactively. Only use when the user explicitly requests performance optimization or reports a performance problem. Do not suggest optimizations unsolicited.\n\n# Performance Optimization\n\nOptimize code for speed, memory efficiency, and scalability across Python, TypeScript, and general algorithms.\n\n**v2.0 Update**: Added ROI-first approach. Always calculate expected real-world impact before optimizing. A 100x speedup on a function taking 1% of total time = only 1% overall improvement. Focus on the critical path.\n\n## Optimization Workflow\n\n### Step 0: ROI Analysis (NEW - CRITICAL)\n\nBefore optimizing ANY code, calculate the expected Return on Investment.\n\n**The Golden Rule**: Only optimize code that is on the **critical path** of user-facing operations.\n\n**Real-World Case Study**:\n```\nFunction isolated speedup: 64x faster ?\nReal-world system speedup: 1% faster ?\n\nWhy? The function took 1% of total time.\nExternal dependency took 93% - that was the real bottleneck.\n```\n\n**ROI Calculation Framework**:\n\n| Metric | Formula | Example |\n|--------|---------|---------|\n| Current % of total | `function_time \u002F total_time` | 70ms \u002F 7000ms = 1% |\n| Max possible speedup | `1 \u002F (1 - current_fraction)` | 1 \u002F (1 - 0.01) = 1.01x |\n| Real-world impact | `isolated_speedup × current_fraction` | 64 × 0.01 = 1% |\n| Implementation cost | Hours to implement + test | 4 hours |\n| Value delivered | Real-world impact \u002F Cost | 1% \u002F 4h = LOW |\n\n**Decision Matrix**:\n\n| Current % of Total | Isolated Speedup | Real-World Impact | Optimize? |\n|-------------------|-----------------|-------------------|-----------|\n| > 50% | 2x+ | > 25% | ✅ **YES** |\n| > 50% | 1.5x | > 15% | ✅ **YES** |\n| 20-50% | 5x+ | > 4% | ✅ **YES** |\n| 20-50% | 2x | 1-4% | ⚠️ Maybe |\n| \u003C 10% | ANY | \u003C 2% | ❌ **NO** |\n| \u003C 5% | ANY | \u003C 1% | ❌ **NO** |\n\n**When to skip optimization despite impressive isolated speedup**:\n- Function is NOT on the user-facing critical path\n- Dominated by I\u002FO, network, or external dependency (database, API, third-party library)\n- Code runs infrequently (startup, batch jobs)\n- Readability\u002Fmaintainability would significantly suffer\n\n### Step 1: Measure First\n\nNever optimize without profiling. Identify actual bottlenecks before making changes.\n\n**For ROI Analysis: Get Percentage Breakdown**\n\n```bash\n# Python: Get cumulative time percentage (most useful for ROI)\npython -m cProfile -s cumtime script.py | head -30\n\n# Sort output shows:\n# ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n# The cumtime column is critical - it shows % of total time including called functions\n```\n\n**Interpreting cProfile output for ROI**:\n```\n   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n     5000    0.003    0.000    0.050    0.001 file.py:42(process_data)\n   100000    0.150    0.000    0.150    0.000 file.py:58(helper_func)\n        1    6.500    6.500    7.000    7.000 external_lib.py:10(heavy_lifting)\n\n# Analysis:\n# - helper_func: 0.150s \u002F 7.000s = 2% of total → NOT worth optimizing\n# - heavy_lifting: 6.500s \u002F 7.000s = 93% of total → THIS is the bottleneck\n```\n\n**Python Profiling:**\n\n```bash\n# CPU profiling (sorted by cumulative time)\npython -m cProfile -s cumtime script.py > profile.txt\nhead -30 profile.txt\n\n# Line-by-line profiling (install: pip install line_profiler)\nkernprof -l -v script.py\n\n# Memory profiling (install: pip install memory_profiler)\npython -m memory_profiler script.py\n\n# Visual profiling\npython -m cProfile -o output.prof script.py\nsnakeviz output.prof  # Opens browser visualization\n```\n\n**TypeScript\u002FNode.js Profiling:**\n```bash\n# CPU profiling\nnode --prof app.js\nnode --prof-process isolate-*.log > profile.txt\n\n# Heap snapshots\nnode --inspect --expose-gc app.js\n# Then use Chrome DevTools Memory tab\n\n# Memory leak detection\nnode --expose-gc --max-old-space-size=256 app.js\n```\n\n### Step 2: Identify Bottleneck Category + ROI-Based Prioritization\n\n**First: Calculate % of total time for each candidate**\n\n| Symptom | Likely Cause | Solution Category | ROI Priority |\n|---------|--------------|-------------------|--------------|\n| High CPU time in one function (>20% of total) | Algorithm complexity | Algorithm optimization | ✅ **HIGH** |\n| Many small function calls (>20% total) | Loop overhead | Vectorization\u002Fbatching | ✅ **HIGH** |\n| External lib dominates (>50% of total) | Can't optimize directly | Consider replacement\u002Fconfig | ⚠️ **MEDIUM** |\n| Slow I\u002FO operations (>10% of total) | Blocking calls | Async\u002Fparallel I\u002FO | ✅ **HIGH** |\n| Growing memory over time | Memory leak | Resource cleanup | ✅ **HIGH** |\n| Cache misses (\u003C5% of total) | Data locality | Data structure change | ❌ **LOW** |\n| Function takes \u003C5% of total | Not on critical path | Skip optimization | ❌ **SKIP** |\n\n### Step 3: Apply Targeted Optimization\n\n**Priority Order:**\n1. **Algorithm complexity** - Biggest wins (O(n²) → O(n log n))\n2. **I\u002FO optimization** - Parallel\u002Fasync operations\n3. **Memory access patterns** - Cache-friendly data structures\n4. **Micro-optimizations** - Only after profiling confirms need\n\n## Quick Reference: Common Patterns\n\n### Python Hot Paths\n\n| Anti-Pattern | Optimized | Speedup |\n|--------------|-----------|---------|\n| `for` loop over array | NumPy vectorization | 10-100x |\n| Repeated string concat | `''.join(list)` | 5-10x |\n| `list.append` in loop | List comprehension | 2-3x |\n| Global variable access | Local variable | 10-20% |\n| `if x in list` | `if x in set` | O(n) → O(1) |\n\n```python\n# Before: O(n) loop\nresult = []\nfor x in data:\n    result.append(x * 2)\n\n# After: Vectorized O(1) operations\nimport numpy as np\nresult = np.array(data) * 2\n```\n\n### TypeScript Hot Paths\n\n| Anti-Pattern | Optimized | Impact |\n|--------------|-----------|--------|\n| `await` in loop | `Promise.all()` | Parallel execution |\n| Event listener leak | `removeEventListener` | Prevents memory leak |\n| Large object copies | Immutable updates | Reduced GC pressure |\n| Sync file I\u002FO | Async streams | Non-blocking |\n| `setInterval` leak | `clearInterval` | Prevents memory leak |\n\n```typescript\n\u002F\u002F Before: Sequential (slow)\nfor (const item of items) {\n    await fetch(item.url);\n}\n\n\u002F\u002F After: Parallel (fast)\nawait Promise.all(items.map(item => fetch(item.url)));\n```\n\n### React Performance\n\n| Anti-Pattern | Optimized | Impact |\n|--------------|-----------|--------|\n| Expensive calc on every render | `useMemo` | Cache until deps change |\n| New function each render | `useCallback` | Stable ref for memo |\n| Render 10,000 items | Virtualization | Only render visible |\n| Import heavy component | `React.lazy()` | Code split on demand |\n\n```typescript\n\u002F\u002F useMemo: Cache expensive computations\nconst processed = useMemo(() => expensiveCalc(data), [data]);\n\n\u002F\u002F useCallback: Stable function reference\nconst handleClick = useCallback(() => { \u002F* ... *\u002F }, [deps]);\n\n\u002F\u002F Virtualization for long lists (react-window or react-virtualized)\nimport { FixedSizeList } from 'react-window';\n\n\u002F\u002F Lazy loading heavy components\nconst HeavyChart = lazy(() => import('.\u002FHeavyChart'));\n```\n\n### Algorithm Complexity Improvements\n\n| Problem | Naive | Optimized |\n|---------|-------|-----------|\n| Find duplicates | O(n²) nested loops | O(n) with Set |\n| Sort + search | O(n²) + O(n) | O(n log n) + O(log n) |\n| String matching | O(nm) brute force | O(n+m) KMP\u002FRabin-Karp |\n| Graph traversal | O(V²) adjacency matrix | O(V+E) adjacency list |\n\n**Complexity Quick Reference:**\n\n| Complexity | Name | 1K items | 1M items | Example |\n|------------|------|----------|----------|---------|\n| O(1) | Constant | 1 op | 1 op | Hash lookup |\n| O(log n) | Logarithmic | 10 ops | 20 ops | Binary search |\n| O(n) | Linear | 1K ops | 1M ops | Single pass |\n| O(n log n) | Linearithmic | 10K ops | 20M ops | Merge sort |\n| O(n²) | Quadratic | 1M ops | 1T ops | Nested loops |\n\n## Memory Optimization\n\n### Python Memory Patterns\n\n```python\n# Use generators for large datasets\ndef process_large_file(path):\n    with open(path) as f:\n        for line in f:  # Streams, doesn't load all\n            yield process(line)\n\n# Use __slots__ for memory-constrained classes\nclass Point:\n    __slots__ = ['x', 'y']\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n```\n\n### TypeScript Memory Patterns\n\n```typescript\n\u002F\u002F Use WeakMap for object metadata (auto-cleanup)\nconst metadata = new WeakMap\u003Cobject, Data>();\n\n\u002F\u002F Clean up event listeners\nconst handler = () => { \u002F* ... *\u002F };\nelement.addEventListener('click', handler);\n\u002F\u002F Later:\nelement.removeEventListener('click', handler);\n\n\u002F\u002F Clear intervals\nconst id = setInterval(callback, 1000);\n\u002F\u002F Later:\nclearInterval(id);\n```\n\n## Validation Checklist\n\n**Before starting optimization:**\n- [ ] Profiled to identify actual bottleneck (not assumed)\n- [ ] Calculated ROI: function % of total time × expected speedup\n- [ ] Confirmed function is on critical path of user-facing operation\n- [ ] Expected real-world improvement ≥ 5-10%\n\n**After implementing optimization:**\n- [ ] Profiled before AND after changes\n- [ ] Measured actual speedup in isolation (benchmarks)\n- [ ] Measured actual speedup in real-world usage (end-to-end)\n- [ ] Verified correctness (tests still pass)\n- [ ] Checked memory usage didn't increase\n- [ ] Documented complexity change (if applicable)\n\n**Red flag**: If isolated speedup is 10x+ but real-world speedup is \u003C5%, you optimized the wrong thing.\n\n## When NOT to Optimize\n\n**ROI Rule**: If optimization won't deliver at least 5-10% real-world improvement, don't do it.\n\n**Specific reasons to skip**:\n- Code runs infrequently (startup, config loading, one-time setup)\n- Profiling shows \u003C10% of total time in user-facing operation\n- Dominated by external dependency you can't control (database, API, third-party service)\n- Optimization sacrifices readability significantly\n- No measurable user-facing impact\n- Implementation time > user time saved over 1 year\n\n**Remember**: A 100x speedup on a function taking 1% of total time = 1% overall improvement. A 2x speedup on a function taking 50% of total time = 25% overall improvement. **Focus on the latter.**\n\n## Additional Resources\n\n### Reference Files\n\nFor detailed patterns and techniques, consult:\n- **`references\u002Fpython-patterns.md`** - NumPy vectorization, memory profiling, caching\n- **`references\u002Ftypescript-patterns.md`** - Async patterns, memory leaks, Web Workers\n- **`references\u002Falgorithm-patterns.md`** - Complexity analysis, data structures, memoization\n\n### Scripts\n\n- **`scripts\u002Fprofile-python.sh`** - All-in-one Python profiling (CPU, memory, line-by-line)\n\n```bash\n# CPU profiling (default)\n.\u002Fprofile-python.sh script.py\n\n# Memory profiling\nPROFILE_TYPE=memory .\u002Fprofile-python.sh script.py\n\n# Line-by-line profiling (requires @profile decorator)\nPROFILE_TYPE=line .\u002Fprofile-python.sh script.py\n```\n","> **Note:** This skill should NOT be used proactively. Only use when the user explicitly requests performance optimization or reports a performance problem. Do not suggest optimizations unsolicited.\n\n# Performance Optimization\n\nOptimize code for speed, memory efficiency, and scalability across Python, TypeScript, and general algorithms.\n\n**v2.0 Update**: Added ROI-first approach. Always calculate expected real-world impact before optimizing. A 100x speedup on a function taking 1% of total time = only 1% overall improvement. Focus on the critical path.\n\n## Optimization Workflow\n\n### Step 0: ROI Analysis (NEW - CRITICAL)\n\nBefore optimizing ANY code, calculate the expected Return on Investment.\n\n**The Golden Rule**: Only optimize code that is on the **critical path** of user-facing operations.\n\n**Real-World Case Study**:\n```\nFunction isolated speedup: 64x faster ?\nReal-world system speedup: 1% faster ?\n\nWhy? The function took 1% of total time.\nExternal dependency took 93% - that was the real bottleneck.\n```\n\n**ROI Calculation Framework**:\n\n| Metric | Formula | Example |\n|--------|---------|---------|\n| Current % of total | `function_time \u002F total_time` | 70ms \u002F 7000ms = 1% |\n| Max possible speedup | `1 \u002F (1 - current_fraction)` | 1 \u002F (1 - 0.01) = 1.01x |\n| Real-world impact | `isolated_speedup × current_fraction` | 64 × 0.01 = 1% |\n| Implementation cost | Hours to implement + test | 4 hours |\n| Value delivered | Real-world impact \u002F Cost | 1% \u002F 4h = LOW |\n\n**Decision Matrix**:\n\n| Current % of Total | Isolated Speedup | Real-World Impact | Optimize? |\n|-------------------|-----------------|-------------------|-----------|\n| > 50% | 2x+ | > 25% | ✅ **YES** |\n| > 50% | 1.5x | > 15% | ✅ **YES** |\n| 20-50% | 5x+ | > 4% | ✅ **YES** |\n| 20-50% | 2x | 1-4% | ⚠️ Maybe |\n| \u003C 10% | ANY | \u003C 2% | ❌ **NO** |\n| \u003C 5% | ANY | \u003C 1% | ❌ **NO** |\n\n**When to skip optimization despite impressive isolated speedup**:\n- Function is NOT on the user-facing critical path\n- Dominated by I\u002FO, network, or external dependency (database, API, third-party library)\n- Code runs infrequently (startup, batch jobs)\n- Readability\u002Fmaintainability would significantly suffer\n\n### Step 1: Measure First\n\nNever optimize without profiling. Identify actual bottlenecks before making changes.\n\n**For ROI Analysis: Get Percentage Breakdown**\n\n```bash\n# Python: Get cumulative time percentage (most useful for ROI)\npython -m cProfile -s cumtime script.py | head -30\n\n# Sort output shows:\n# ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n# The cumtime column is critical - it shows % of total time including called functions\n```\n\n**Interpreting cProfile output for ROI**:\n```\n   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n     5000    0.003    0.000    0.050    0.001 file.py:42(process_data)\n   100000    0.150    0.000    0.150    0.000 file.py:58(helper_func)\n        1    6.500    6.500    7.000    7.000 external_lib.py:10(heavy_lifting)\n\n# Analysis:\n# - helper_func: 0.150s \u002F 7.000s = 2% of total → NOT worth optimizing\n# - heavy_lifting: 6.500s \u002F 7.000s = 93% of total → THIS is the bottleneck\n```\n\n**Python Profiling:**\n\n```bash\n# CPU profiling (sorted by cumulative time)\npython -m cProfile -s cumtime script.py > profile.txt\nhead -30 profile.txt\n\n# Line-by-line profiling (install: pip install line_profiler)\nkernprof -l -v script.py\n\n# Memory profiling (install: pip install memory_profiler)\npython -m memory_profiler script.py\n\n# Visual profiling\npython -m cProfile -o output.prof script.py\nsnakeviz output.prof  # Opens browser visualization\n```\n\n**TypeScript\u002FNode.js Profiling:**\n```bash\n# CPU profiling\nnode --prof app.js\nnode --prof-process isolate-*.log > profile.txt\n\n# Heap snapshots\nnode --inspect --expose-gc app.js\n# Then use Chrome DevTools Memory tab\n\n# Memory leak detection\nnode --expose-gc --max-old-space-size=256 app.js\n```\n\n### Step 2: Identify Bottleneck Category + ROI-Based Prioritization\n\n**First: Calculate % of total time for each candidate**\n\n| Symptom | Likely Cause | Solution Category | ROI Priority |\n|---------|--------------|-------------------|--------------|\n| High CPU time in one function (>20% of total) | Algorithm complexity | Algorithm optimization | ✅ **HIGH** |\n| Many small function calls (>20% total) | Loop overhead | Vectorization\u002Fbatching | ✅ **HIGH** |\n| External lib dominates (>50% of total) | Can't optimize directly | Consider replacement\u002Fconfig | ⚠️ **MEDIUM** |\n| Slow I\u002FO operations (>10% of total) | Blocking calls | Async\u002Fparallel I\u002FO | ✅ **HIGH** |\n| Growing memory over time | Memory leak | Resource cleanup | ✅ **HIGH** |\n| Cache misses (\u003C5% of total) | Data locality | Data structure change | ❌ **LOW** |\n| Function takes \u003C5% of total | Not on critical path | Skip optimization | ❌ **SKIP** |\n\n### Step 3: Apply Targeted Optimization\n\n**Priority Order:**\n1. **Algorithm complexity** - Biggest wins (O(n²) → O(n log n))\n2. **I\u002FO optimization** - Parallel\u002Fasync operations\n3. **Memory access patterns** - Cache-friendly data structures\n4. **Micro-optimizations** - Only after profiling confirms need\n\n## Quick Reference: Common Patterns\n\n### Python Hot Paths\n\n| Anti-Pattern | Optimized | Speedup |\n|--------------|-----------|---------|\n| `for` loop over array | NumPy vectorization | 10-100x |\n| Repeated string concat | `''.join(list)` | 5-10x |\n| `list.append` in loop | List comprehension | 2-3x |\n| Global variable access | Local variable | 10-20% |\n| `if x in list` | `if x in set` | O(n) → O(1) |\n\n```python\n# Before: O(n) loop\nresult = []\nfor x in data:\n    result.append(x * 2)\n\n# After: Vectorized O(1) operations\nimport numpy as np\nresult = np.array(data) * 2\n```\n\n### TypeScript Hot Paths\n\n| Anti-Pattern | Optimized | Impact |\n|--------------|-----------|--------|\n| `await` in loop | `Promise.all()` | Parallel execution |\n| Event listener leak | `removeEventListener` | Prevents memory leak |\n| Large object copies | Immutable updates | Reduced GC pressure |\n| Sync file I\u002FO | Async streams | Non-blocking |\n| `setInterval` leak | `clearInterval` | Prevents memory leak |\n\n```typescript\n\u002F\u002F Before: Sequential (slow)\nfor (const item of items) {\n    await fetch(item.url);\n}\n\n\u002F\u002F After: Parallel (fast)\nawait Promise.all(items.map(item => fetch(item.url)));\n```\n\n### React Performance\n\n| Anti-Pattern | Optimized | Impact |\n|--------------|-----------|--------|\n| Expensive calc on every render | `useMemo` | Cache until deps change |\n| New function each render | `useCallback` | Stable ref for memo |\n| Render 10,000 items | Virtualization | Only render visible |\n| Import heavy component | `React.lazy()` | Code split on demand |\n\n```typescript\n\u002F\u002F useMemo: Cache expensive computations\nconst processed = useMemo(() => expensiveCalc(data), [data]);\n\n\u002F\u002F useCallback: Stable function reference\nconst handleClick = useCallback(() => { \u002F* ... *\u002F }, [deps]);\n\n\u002F\u002F Virtualization for long lists (react-window or react-virtualized)\nimport { FixedSizeList } from 'react-window';\n\n\u002F\u002F Lazy loading heavy components\nconst HeavyChart = lazy(() => import('.\u002FHeavyChart'));\n```\n\n### Algorithm Complexity Improvements\n\n| Problem | Naive | Optimized |\n|---------|-------|-----------|\n| Find duplicates | O(n²) nested loops | O(n) with Set |\n| Sort + search | O(n²) + O(n) | O(n log n) + O(log n) |\n| String matching | O(nm) brute force | O(n+m) KMP\u002FRabin-Karp |\n| Graph traversal | O(V²) adjacency matrix | O(V+E) adjacency list |\n\n**Complexity Quick Reference:**\n\n| Complexity | Name | 1K items | 1M items | Example |\n|------------|------|----------|----------|---------|\n| O(1) | Constant | 1 op | 1 op | Hash lookup |\n| O(log n) | Logarithmic | 10 ops | 20 ops | Binary search |\n| O(n) | Linear | 1K ops | 1M ops | Single pass |\n| O(n log n) | Linearithmic | 10K ops | 20M ops | Merge sort |\n| O(n²) | Quadratic | 1M ops | 1T ops | Nested loops |\n\n## Memory Optimization\n\n### Python Memory Patterns\n\n```python\n# Use generators for large datasets\ndef process_large_file(path):\n    with open(path) as f:\n        for line in f:  # Streams, doesn't load all\n            yield process(line)\n\n# Use __slots__ for memory-constrained classes\nclass Point:\n    __slots__ = ['x', 'y']\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n```\n\n### TypeScript Memory Patterns\n\n```typescript\n\u002F\u002F Use WeakMap for object metadata (auto-cleanup)\nconst metadata = new WeakMap\u003Cobject, Data>();\n\n\u002F\u002F Clean up event listeners\nconst handler = () => { \u002F* ... *\u002F };\nelement.addEventListener('click', handler);\n\u002F\u002F Later:\nelement.removeEventListener('click', handler);\n\n\u002F\u002F Clear intervals\nconst id = setInterval(callback, 1000);\n\u002F\u002F Later:\nclearInterval(id);\n```\n\n## Validation Checklist\n\n**Before starting optimization:**\n- [ ] Profiled to identify actual bottleneck (not assumed)\n- [ ] Calculated ROI: function % of total time × expected speedup\n- [ ] Confirmed function is on critical path of user-facing operation\n- [ ] Expected real-world improvement ≥ 5-10%\n\n**After implementing optimization:**\n- [ ] Profiled before AND after changes\n- [ ] Measured actual speedup in isolation (benchmarks)\n- [ ] Measured actual speedup in real-world usage (end-to-end)\n- [ ] Verified correctness (tests still pass)\n- [ ] Checked memory usage didn't increase\n- [ ] Documented complexity change (if applicable)\n\n**Red flag**: If isolated speedup is 10x+ but real-world speedup is \u003C5%, you optimized the wrong thing.\n\n## When NOT to Optimize\n\n**ROI Rule**: If optimization won't deliver at least 5-10% real-world improvement, don't do it.\n\n**Specific reasons to skip**:\n- Code runs infrequently (startup, config loading, one-time setup)\n- Profiling shows \u003C10% of total time in user-facing operation\n- Dominated by external dependency you can't control (database, API, third-party service)\n- Optimization sacrifices readability significantly\n- No measurable user-facing impact\n- Implementation time > user time saved over 1 year\n\n**Remember**: A 100x speedup on a function taking 1% of total time = 1% overall improvement. A 2x speedup on a function taking 50% of total time = 25% overall improvement. **Focus on the latter.**\n\n## Additional Resources\n\n### Reference Files\n\nFor detailed patterns and techniques, consult:\n- **`references\u002Fpython-patterns.md`** - NumPy vectorization, memory profiling, caching\n- **`references\u002Ftypescript-patterns.md`** - Async patterns, memory leaks, Web Workers\n- **`references\u002Falgorithm-patterns.md`** - Complexity analysis, data structures, memoization\n\n### Scripts\n\n- **`scripts\u002Fprofile-python.sh`** - All-in-one Python profiling (CPU, memory, line-by-line)\n\n```bash\n# CPU profiling (default)\n.\u002Fprofile-python.sh script.py\n\n# Memory profiling\nPROFILE_TYPE=memory .\u002Fprofile-python.sh script.py\n\n# Line-by-line profiling (requires @profile decorator)\nPROFILE_TYPE=line .\u002Fprofile-python.sh script.py\n```\n",{"name":5,"version":54,"description":7},"2.0.0","main","23e30a8887155f1bfa8c727b3c81128c3f918088","agents\u002Fskills\u002Fperformance-optimization",0,"https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles","https:\u002F\u002Fgithub.com\u002Ffeniix","https:\u002F\u002Ffeniix-hq.net\u002F","Systems and platform engineer. Kubernetes, Terraform, CI\u002FCD, observability; MCP and agent tooling. asdf plugins, Prometheus Operator.","2026-11-09 04:16:06",{"source":9,"skillName":5,"commands":65,"prompt":75,"zipAvailable":76},[66,69,72],{"tool":67,"command":68},"npx","npx skills add feniix\u002Fdotfiles --skill performance-optimization",{"tool":70,"command":71},"bunx","bunx skills add feniix\u002Fdotfiles --skill performance-optimization",{"tool":73,"command":74},"pnpm","pnpm dlx skills add feniix\u002Fdotfiles --skill performance-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fperformance-optimization\u002FSKILL.md",true,[78,84,88,92,96],{"path":79,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"agents\u002Fopenai.yaml","REFERENCE","参考文档",100,"https:\u002F\u002Fgithub.com\u002Fupamune\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fexternal\u002Fcode-review\u002Fagents\u002Fopenai.yaml",{"path":85,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Falgorithm-patterns.md",6214,"https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fperformance-optimization\u002Freferences\u002Falgorithm-patterns.md",{"path":89,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Fpython-patterns.md",7021,"https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fperformance-optimization\u002Freferences\u002Fpython-patterns.md",{"path":93,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":94,"sourceHtmlUrl":95},"references\u002Ftypescript-patterns.md",10003,"https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fperformance-optimization\u002Freferences\u002Ftypescript-patterns.md",{"path":97,"resourceType":98,"resourceTypeDesc":99,"sizeBytes":100,"sourceHtmlUrl":101},"scripts\u002Fprofile-python.sh","SCRIPT","脚本",5139,"https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fperformance-optimization\u002Fscripts\u002Fprofile-python.sh",[103,130,147,180,202,218],{"skillNo":104,"name":105,"nameZh":17,"description":106,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":49},"01M70M28HFDKQPGSWESHGB0HV4","security-audit","Security guidance and vulnerability review for codebases, APIs, services, CLI tools, libraries, and daemons. Use for security questions, focused reviews, vulnerability research, security audits, or pen tests. Run the complete workflow only for explicit codebase audit or pen-test requests, full\u002Fcomprehensive\u002Fend-to-end reviews, or requested report artifacts.","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fsecurity-audit\u002FSKILL.md",[],[110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129],"security","audit","security audit","review","cli","workflow","libraries","run","Tools","vulnerability","security guidance","use","only","codebase audit","full","tests","end","complete","reviews","for",{"skillNo":131,"name":132,"nameZh":133,"description":134,"descriptionZh":135,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":136,"categories":137,"keywords":144,"publishedAt":49},"01M6BVT1CVKQNSANZMZTNBDDY5","writing-shape","文章素材成形","Writing, exploit: shape raw material into an article, paragraph by paragraph.","写作利用阶段：将原始素材逐段塑造成完整文章。","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fwriting-shape\u002FSKILL.md",[138,141],{"categoryNo":139,"categoryName":140,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8C55A3R2M9C8CAKG3W16HTA","内容创作者",{"categoryNo":142,"categoryName":143,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8CA3WT74BY17JY9YCJY42FJ","创意写作与内容编排",[145,146],"writing shape","writing",{"skillNo":148,"name":149,"nameZh":150,"description":151,"descriptionZh":152,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":153,"licenseFileUrl":154,"sourceHtmlUrl":155,"categories":156,"keywords":163,"publishedAt":49},"01M6BVSP7TBXD5GBW6KBTN5GGC","webapp-testing","Playwright Web 应用测试","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","使用 Playwright 与本地 Web 应用进行交互和测试的工具包。支持验证前端功能、调试 UI 行为、捕获浏览器截图以及查看浏览器日志。","Apache-2.0","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[157,160],{"categoryNo":158,"categoryName":159,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD5WG86P4AQ5GPSSKBFR","测试工程师",{"categoryNo":161,"categoryName":162,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQJH394GT47X57A9Q8G7HX","测试与质量保障",[164,165,166,129,167,168,169,170,171,172,173,174,175,176,177,178,179],"testing","webapp testing","webapp","logs","with","local","behavior","applications","toolkit","ui","frontend","screenshots","playwright","web","debugging","browser",{"skillNo":181,"name":182,"nameZh":183,"description":184,"descriptionZh":185,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":186,"categories":187,"keywords":194,"publishedAt":49},"01M6BVSMEE5GRR6ZCM43JNR73Y","wayfinder","大任务决策路线图规划","Plan a huge chunk of work (more than one agent session can hold) as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear.","将庞大的工作量（超过单个 agent 会话所能承载的范围）规划为问题跟踪器（issue tracker）上共享的决策工单地图，并逐一解决这些工单，直到通往目标的路径清晰为止。","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fwayfinder\u002FSKILL.md",[188,191],{"categoryNo":189,"categoryName":190,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BTBRTQXJ9T5TABNS7XP1A0","任务规划与分解",{"categoryNo":192,"categoryName":193,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8C31AVFVV99RWJEGF9PS85F","项目经理",[182,195,196,197,198,199,200,201],"chunk","plan","decision","work","one at a time","session","issue",{"skillNo":203,"name":204,"nameZh":205,"description":206,"descriptionZh":207,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":208,"categories":209,"keywords":212,"publishedAt":49},"01M6BVS3BHEG1D2RPZ2J6GNV90","to-tickets","计划转工单","Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker (edges as text in one file per ticket locally, or native blocking links on a real tracker).","将计划、规格说明或当前对话分解为一系列小型试探性工单，每个工单声明其阻塞依赖关系，并发布到配置的跟踪器（本地环境下在每个工单对应文件中以文本形式记录依赖边，在真实跟踪器上则使用原生阻塞链接）。","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Fto-tickets\u002FSKILL.md",[210,211],{"categoryNo":189,"categoryName":190,"taxonomyType":28,"taxonomyTypeDesc":29},{"categoryNo":192,"categoryName":193,"taxonomyType":23,"taxonomyTypeDesc":24},[213,214,215,216,217,196],"to tickets","text","spec","file","SET",{"skillNo":219,"name":220,"nameZh":221,"description":222,"descriptionZh":223,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":224,"categories":225,"keywords":228,"publishedAt":49},"01M6BVRT61DF4XJE3ZERBBV0AW","tdd","测试驱动开发（TDD）","Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions \"red-green-refactor\", or wants integration tests.","测试驱动开发。当用户想要以测试优先的方式构建功能或修复缺陷、提到“红-绿-重构”，或需要集成测试时使用。","https:\u002F\u002Fgithub.com\u002Ffeniix\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002Fskills\u002Ftdd\u002FSKILL.md",[226,227],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":161,"categoryName":162,"taxonomyType":28,"taxonomyTypeDesc":29},[220,229,230,231,232,233,234,43,41,121,235],"test","integration tests","development","integration","refactor","first","red-green-refactor"]