complexity-optimizer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Complexity Optimizer

复杂度优化器

Core Rule

核心规则

Optimize only when the current behavior is understood and can be preserved. Prefer a small, proven improvement with tests over a broad rewrite with unclear correctness.
仅在充分理解并能保留现有功能的前提下进行优化。相较于正确性存疑的大规模重写,优先选择经过测试的小幅改进方案。

Default Behavior

默认行为

When the user asks to analyze, scan, audit, review, or "give me a report" for a codebase, produce the full complexity report automatically. Do not require the user to specify report fields.
Default report contents:
  • Scope analyzed and detected stack/test commands.
  • Top findings ranked by likely impact.
  • File and line for each finding.
  • Current pattern and why it may be costly.
  • Estimated current complexity.
  • Recommended change.
  • Estimated complexity after the change.
  • Risk level.
  • Tests, benchmarks, or manual checks needed.
  • Clear statement that no files were modified, unless the user explicitly requested implementation.
Only edit files when the user asks to implement, fix, optimize, apply, change, refactor, or otherwise clearly requests code modification. If the user only asks for analysis or a report, do not modify files.
当用户要求分析、扫描、审计、审查代码库或“生成一份报告”时,自动生成完整的复杂度报告,无需用户指定报告字段。
默认报告内容:
  • 分析范围及检测到的堆栈/测试命令。
  • 按潜在影响排序的关键发现。
  • 每个发现对应的文件及行号。
  • 当前代码模式及其高成本原因。
  • 当前复杂度估算值。
  • 推荐的修改方案。
  • 修改后的复杂度估算值。
  • 风险等级。
  • 需要执行的测试、基准测试或手动检查项。
  • 明确说明未修改任何文件,除非用户明确要求实施优化。
仅当用户要求实施、修复、优化、应用、更改、重构或以其他明确方式要求修改代码时,才编辑文件。若用户仅要求分析或生成报告,则不得修改文件。

Workflow

工作流程

  1. Establish the baseline:
    • Identify the language, framework, test command, build command, and performance-sensitive paths.
    • Inspect existing tests before touching code.
    • Run
      scripts/analyze_complexity.py <repo>
      for a first-pass hotspot list when scanning a repository.
  2. Rank opportunities:
    • Prioritize code on hot paths, large input paths, rendering loops, database/API loops, and shared utilities.
    • Separate algorithmic complexity from constant-factor cleanup.
    • Do not patch every warning. Treat scanner output as leads, not proof.
    • For report-only requests, inspect enough surrounding code to estimate current and proposed complexity; do not stop at raw scanner output.
  3. Prove behavior:
    • Locate or add focused tests for the function/component being changed.
    • Capture edge cases: empty input, duplicates, ordering stability, null/missing values, errors, permissions, pagination, time zones, and mutation side effects.
    • If tests are absent and behavior is ambiguous, make the smallest refactor or ask for expected behavior before changing semantics.
  4. Optimize conservatively:
    • Replace repeated linear lookup with maps/sets when key equality is stable.
    • Replace nested scans with indexing, grouping, two-pointer scans, sweep-line logic, binary search, memoization, batching, or precomputation only when the data shape supports it.
    • In UI code, reduce unnecessary renders with stable props, memoized derived data, virtualization, debounced work, and moving expensive work out of render paths.
    • In data access code, remove N+1 behavior with bulk fetches, joins, preloading, caching, or batching while preserving authorization and filtering.
  5. Verify:
    • Run relevant tests and type/lint/build commands.
    • Add a micro-benchmark or measurement when the complexity improvement is non-obvious or performance-critical.
    • Report the original complexity, new complexity, changed files, tests run, and any residual risk.
  1. 建立基准:
    • 识别编程语言、框架、测试命令、构建命令及性能敏感路径。
    • 在修改代码前检查现有测试用例。
    • 扫描代码库时,运行
      scripts/analyze_complexity.py <repo>
      生成初步的性能热点列表。
  2. 排序优化机会:
    • 优先处理热点路径、大输入路径、渲染循环、数据库/API循环及共享工具类中的代码。
    • 区分算法复杂度问题与常数因子优化。
    • 无需修复所有警告,将扫描工具的输出视为线索而非定论。
    • 对于仅要求生成报告的请求,需检查足够的周边代码以估算当前及建议的复杂度,不能仅停留在扫描工具的原始输出。
  3. 验证功能一致性:
    • 为待修改的函数/组件查找或添加针对性测试用例。
    • 覆盖边缘场景:空输入、重复值、排序稳定性、空值/缺失值、错误、权限、分页、时区及突变副作用。
    • 若缺少测试用例且功能不明确,应先进行最小化重构或询问预期行为,再修改语义。
  4. 保守优化:
    • 当键值相等性稳定时,用映射/集合替代重复的线性查找。
    • 仅当数据结构支持时,用索引、分组、双指针扫描、扫描线逻辑、二分查找、记忆化、批处理或预计算替代嵌套扫描。
    • 在UI代码中,通过稳定的props、记忆化派生数据、虚拟化、防抖处理及将高成本操作移出渲染路径来减少不必要的渲染。
    • 在数据访问代码中,通过批量获取、连接查询、预加载、缓存或批处理消除N+1查询问题,同时保留授权与过滤规则。
  5. 验证优化结果:
    • 运行相关测试及类型检查/代码检查/构建命令。
    • 当复杂度改进不明显或对性能至关重要时,添加微基准测试或性能度量。
    • 报告原始复杂度、新复杂度、修改的文件、运行的测试及任何剩余风险。

First-Pass Scanner

初步扫描工具

Use the bundled scanner from the skill directory:
bash
python3 scripts/analyze_complexity.py /path/to/repo --format markdown
python3 scripts/analyze_complexity.py /path/to/repo --format json
The scanner flags common patterns in Python, JavaScript, TypeScript, JSX/TSX, Java, Go, C, C++, C#, Ruby, PHP, and Swift files. It intentionally favors readable leads over perfect static analysis.
If the scanner reports nothing, still inspect known hot paths manually. Rendering churn, database query patterns, and framework lifecycle issues often require repository-specific context.
使用技能目录中自带的扫描工具:
bash
python3 scripts/analyze_complexity.py /path/to/repo --format markdown
python3 scripts/analyze_complexity.py /path/to/repo --format json
该扫描工具可标记Python、JavaScript、TypeScript、JSX/TSX、Java、Go、C、C++、C#、Ruby、PHP及Swift文件中的常见问题模式。它优先提供易读的线索,而非追求完美的静态分析。
若扫描工具未报告任何问题,仍需手动检查已知的热点路径。渲染波动、数据库查询模式及框架生命周期问题通常需要结合代码库的特定上下文进行分析。

Optimization Safety Checklist

优化安全检查清单

Before editing:
  • Confirm the data sizes are large enough for complexity to matter.
  • Confirm the optimization preserves output ordering where callers may rely on it.
  • Confirm object identity, mutability, and reference sharing are not part of the public behavior.
  • Confirm caches have a valid invalidation strategy.
  • Confirm deduplication does not collapse distinct records that share a display label.
  • Confirm database batching preserves tenant, permission, soft-delete, pagination, and sorting constraints.
After editing:
  • Run the narrow test first, then the broadest relevant test/build command.
  • Compare before/after benchmark numbers when a benchmark exists or was added.
  • Keep the patch localized. Avoid formatting churn in unrelated files.
修改代码前:
  • 确认数据规模足够大,复杂度优化确实有意义。
  • 确认优化方案保留了调用方可能依赖的输出顺序。
  • 确认对象标识、可变性及引用共享不属于公开功能的一部分。
  • 确认缓存有有效的失效策略。
  • 确认去重操作不会合并具有相同显示标签但实际不同的记录。
  • 确认数据库批处理保留了租户、权限、软删除、分页及排序约束。
修改代码后:
  • 先运行针对性测试,再运行最广泛的相关测试/构建命令。
  • 若存在基准测试或已添加基准测试,对比优化前后的基准测试数据。
  • 保持修改范围局部化,避免在无关文件中引入格式变更。

References

参考资料

  • Read
    references/optimization-playbook.md
    for common O(n^2) to O(n log n) / O(n) transformations and framework-specific patterns.
  • Read
    references/report-template.md
    when preparing the final analysis or audit output.
  • 阅读
    references/optimization-playbook.md
    ,了解常见的从O(n²)到O(n log n)/O(n)的转换方法及框架特定模式。
  • 准备最终分析或审计输出时,参考
    references/report-template.md