← 返回
未分类

code-optimizer-skill

Use when code has performance issues, slow execution, high memory usage, nested loops, timeout errors, TLE, or fails performance benchmarks. Also use for algorithm complexity analysis, data structure optimization, or when user mentions Big O, O(n^2), time/space complexity, performance tuning, optimize, speed up code in C++, Java, or Python.
Use when code has performance issues, slow execution, high memory usage, nested loops, timeout errors, TLE, or fails performance benchmarks. Also use for algorithm complexity analysis, data structure optimization, or when user mentions Big O, O(n^2), time/space complexity, performance tuning, optimize, speed up code in C++, Java, or Python.
for the skill
未分类 community v1.0.1 2 版本 99285.7 Key: 无需
★ 0
Stars
📥 139
下载
💾 6
安装
2
版本
#latest

概述

Code Optimizer Skill

Overview

Transform code to reduce time and space complexity while maintaining correctness. Focus on proven optimization patterns across C++, Java, and Python.

Core principle: Measurably improve complexity, verify behavior unchanged.

When to Use

Use for ANY performance-related work:

  • Slow code, timeouts, memory issues
  • Nested loops, repeated lookups
  • Algorithm/data structure selection
  • Complexity analysis requests

Use ESPECIALLY when:

  • User mentions "optimize", "speed up", "performance"
  • Code has O(N^2) or worse patterns
  • Timeout errors (TLE) in competitive programming
  • Memory pressure or GC overhead issues

Quick Reference

SymptomLikely IssueQuick Fix
----------------------------------
Nested loops over same dataO(N^2)Hash table or two pointers
Lookup in unsorted listO(N) per lookupConvert to set/hash
String concat in loopO(N^2) memory churnStringBuilder/reserve
Repeated sortingO(N log N) eachSort once, cache sorted
Recursion explosionExponentialMemoization/DP
Vector growth without reserveMultiple allocationsPre-allocate capacity

Optimization Workflow

Follow these steps for every optimization:

Optimization Progress:
- [ ] Step 1: Identify current complexity
- [ ] Step 2: Analyze bottleneck source
- [ ] Step 3: Select optimization strategy
- [ ] Step 4: Implement minimal change
- [ ] Step 5: Verify complexity improvement
- [ ] Step 6: Confirm behavior unchanged

Step 1: Identify current complexity

  • Count loop nesting depth
  • Identify data structure operations (lookup, insert, iterate)
  • Calculate worst-case operations count
  • Express as Big O notation

Step 2: Analyze bottleneck source

PatternLikely Bottleneck
----------------------------
Nested iteration over same dataO(N^2) from double loop
Lookup in unsorted list/arrayO(N) per lookup
Repeated sortingO(N log N) per sort
String concatenation in loopO(N^2) from repeated copies
Recursion without memoizationExponential branching
Large object creation in loopMemory pressure + GC overhead

Step 3: Select optimization strategy

See Algorithm Selection Decision Tree below.

Step 4: Implement minimal change

  • ONE change at a time
  • No bundled refactoring
  • No "while I'm here" improvements

Step 5: Verify complexity improvement

  • Recalculate Big O
  • Confirm improvement target achieved
  • Test with increasing input sizes

Step 6: Confirm behavior unchanged

  • Run existing tests
  • Manual verification of edge cases
  • Output comparison before/after

Algorithm Selection Decision Tree

digraph algorithm_selection {
    rankdir=TB;

    "Nested loops identified?" [shape=diamond];
    "Lookup operation?" [shape=diamond];
    "Hash Table\n(O(1) lookup)" [shape=box, style=filled, fillcolor="#ccffcc"];
    "Range query?" [shape=diamond];
    "Tree/Heap\n(O(log N) query)" [shape=box, style=filled, fillcolor="#ccffcc"];
    "Sliding pattern?" [shape=diamond];
    "Two Pointers/Window\n(O(N))" [shape=box, style=filled, fillcolor="#ccffcc"];
    "Subproblem reuse?" [shape=diamond];
    "DP/Memoization\n(Polynomial)" [shape=box, style=filled, fillcolor="#ccffcc"];
    "Ordering needed?" [shape=diamond];
    "Pre-sort once\n(O(N log N))" [shape=box, style=filled, fillcolor="#ccffcc"];
    "Keep nested loops\n(document constraint)" [shape=box, style=filled, fillcolor="#ffcccc"];

    "Nested loops identified?" -> "Lookup operation?";
    "Lookup operation?" -> "Hash Table\n(O(1) lookup)" [label="yes"];
    "Lookup operation?" -> "Range query?";
    "Range query?" -> "Tree/Heap\n(O(log N) query)" [label="yes"];
    "Range query?" -> "Sliding pattern?";
    "Sliding pattern?" -> "Two Pointers/Window\n(O(N))" [label="yes"];
    "Sliding pattern?" -> "Subproblem reuse?";
    "Subproblem reuse?" -> "DP/Memoization\n(Polynomial)" [label="yes"];
    "Subproblem reuse?" -> "Ordering needed?";
    "Ordering needed?" -> "Pre-sort once\n(O(N log N))" [label="yes"];
    "Ordering needed?" -> "Keep nested loops\n(document constraint)" [label="no - inherent O(N^2)"];
}

Decision explanations:

DecisionConditionStrategyResult
---------------------------------------
Hash TableRepeated lookup neededReplace list lookup with set/mapO(N) -> O(1) per lookup
Tree/HeapNeed min/max/range queriesUse ordered structureO(N) -> O(log N) per query
Two PointersContiguous range patternReplace nested loop with pointersO(N^2) -> O(N)
DP/MemoSame subproblems calculatedCache resultsO(2^N) -> O(N) or O(N^2)
Pre-sortOrdering enables simpler logicSort once, use sorted propertyVaries

Common Anti-Patterns Summary

Anti-PatternDetection SignalImpactFix
---------------------------------------------
List lookup in loopin list inside forO(N^2)Use set()
String concat in loop+= on strings in loopO(N^2) memoryStringBuilder
Unreserved growthpush_back/append onlyMultiple allocations.reserve(N)
Repeated sortingsort() inside loopO(N log N) eachSort once
Recursion explosionRecursive call, no memoO(2^N)Memoization

Full anti-pattern details: See references/anti-patterns.md

Optimization patterns library: See references/optimization-patterns.md

Complete examples: See references/examples.md

Complexity formulas: See references/complexity-formulas.md

Language-Specific Quick Tips

LanguageKey Optimizations
-----------------------------
C++reserve(), unordered_map, move semantics, std::span, range-based algorithms
JavaStringBuilder with capacity, primitive streams (IntStream), ArrayDeque
PythonList comprehensions, collections module, generators, set() for membership

Red Flags - STOP and Investigate

If you catch yourself thinking:

  • "Just make it faster" without measuring
  • "Optimization is obvious" without analysis
  • "Tests still pass so it's fine" without complexity check
  • "I'll optimize later" in hot path code
  • Skip verification after optimization

All of these mean: STOP. Follow the workflow.

Common Rationalizations

ExcuseReality
-----------------
"Issue is simple, no need to analyze"Simple issues have root causes too. Calculate first.
"Just try this fix first"First fix sets the pattern. Do it right from the start.
"Tests pass so optimization works"Tests pass != complexity improved. Measure.
"Multiple optimizations at once"Can't isolate what worked. One change only.
"I'll measure later"Measurement proves optimization. Do it now.

When NOT to Optimize

  • Code already O(N) or O(N log N) with acceptable performance
  • Premature optimization in prototype/exploration
  • Hot path identified but not yet measured
  • Complexity inherent to problem (e.g., all pairs must be checked)

Decision Logic: When to Ask Questions

DO NOT guess constraints for critical performance code. Ask:

  • "What is the maximum input size?"
  • "Is this latency-sensitive or throughput-sensitive?"
  • "Are there memory limits to consider?"
  • "What is the target time/space complexity?"

Performance Verification

Before claiming optimization success:

Language-specific profiling commands:

C++:

g++ -O2 -pg solution.cpp -o solution
./solution input.txt
gprof solution gmon.out > analysis.txt

Java:

java -Xprof Solution

Python:

python -m cProfile -s tottime solution.py

Scaling test:

for size in 100 1000 10000 100000; do
    time ./solution input_${size}.txt
done
# Expected: Linear scaling for O(N), log-linear for O(N log N)
# Warning: Quadratic scaling (2x size -> 4x time) indicates O(N^2)

版本历史

共 2 个版本

  • v1.0.1 加强功能 当前
    2026-05-18 14:40 安全 安全
  • v1.0.0 Initial release
    2026-04-22 17:35 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

ai-intelligence

Self-Improving + Proactive Agent

ivangdavila
自我反思+自我批评+自我学习+自组织记忆。智能体评估自身工作、发现错误并持续改进。
★ 1,363 📥 319,019
security-compliance

Skill Vetter

spclaudehome
AI智能体技能安全预审工具。安装ClawdHub、GitHub等来源技能前,检查风险信号、权限范围及可疑模式。
★ 1,219 📥 266,831
ai-intelligence

self-improving agent

pskoett
捕获经验教训、错误和纠正,以实现持续改进。使用时机:(1)命令或操作意外失败;(2)用户纠正……
★ 4,062 📥 799,765