关于 optimize-performance
用于识别并修复 Rails 应用性能瓶颈的技能。它要求先测量基线并编写失败的回归测试,再进行优化;数据库变更还需用 EXPLAIN ANALYZE 检查。
主要功能
- 01要求测量性能基线
- 02修复前先写失败的回归测试
- 03使用查询次数断言
- 04数据库变更运行 EXPLAIN ANALYZE
- 05规定七步报告格式
适用场景
- 01调查缓慢的 Rails 端点
- 02减少过多的数据库查询
- 03检查查询或索引变更
- 04记录性能优化过程
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ igmarin/ rails-agent-skills --skill optimize-performance安装后在 Claude Code 中输入/optimize-performance确认已加载。
附带文件EXAMPLES.mdreferences/tools.md
详细介绍
优化性能
识别并修复 Rails 应用中的性能瓶颈。
快速参考
| 工具 | 用途 |
|---|---|
bullet | 在开发环境中检测 N+1 |
rack-mini-profiler | 端点耗时细分 |
EXPLAIN ANALYZE | 查询计划分析 |
HARD-GATE
NEVER optimize without a baseline measurement
ALWAYS write a regression spec before optimizing (query count assertion)
ALWAYS verify with EXPLAIN ANALYZE for database changes
NEVER write the report as "I applied includes(:author), then wrote a spec
to lock it in." The spec MUST be written and shown failing BEFORE the fix
appears in your output. Reordering for narrative flow fails the audit even
when the underlying work was correct.
输出风格
完成性能优化时,输出必须遵循以下七步报告顺序。每一步都必须出现在输出中:
# Performance Optimization — [Description]
## 1. Baseline
<N> queries for <endpoint/action> — source: <log line / profiler output>
## 2. Bottleneck
<N+1 on association X / missing index on column Y> — tool: <bullet / rack-mini-profiler / EXPLAIN ANALYZE>
## 3. Regression Spec — RED
`make_database_queries(count: <N>)` at <path>:<line> — failure: expected <M>, got <N>
## 4. Fix
<path>:<line> — <includes(:association) / add_index / cache block>
## 5. Regression Spec — GREEN
Spec passes ✓ (<M> queries)
## 6. EXPLAIN ANALYZE
Before: Seq Scan, actual time=<X>ms → After: Index Scan, actual time=<Y>ms
## 7. Quantified Improvement
Queries: <N> → <M> | p95: <X>ms → <Y>ms
语言:除非明确要求其他语言,否则使用英语。
扩展资源
不太明显的优化
# Use counter_cache to avoid COUNT queries in loops
# In migration: add_column :users, :posts_count, :integer, default: 0
# In Post model: belongs_to :user, counter_cache: true
user.posts_count # no extra query
回归测试规格(查询次数断言)
RSpec.describe "Post index performance" do
it "loads posts with authors in a fixed number of queries" do
create_list(:post, 10, :with_author)
expect do
get posts_path
end.to make_database_queries(count: 2) # 1 posts query + 1 authors query
end
end
使用 db-query-matchers gem 或自定义的 make_database_queries 匹配器。
在应用索引或查询更改后,直接在 rails dbconsole(PostgreSQL)中运行:
EXPLAIN ANALYZE
SELECT posts.*, users.name
FROM posts
INNER JOIN users ON users.id = posts.author_id
WHERE posts.published = true;
参考文件与外部链接
仅在需要其特定内容时加载这些文件:
- references/tools.md — 当你需要 Bullet、rack-mini-profiler 或 EXPLAIN ANALYZE 的详细配置和安装步骤时使用
外部参考:
集成
| 技能 | 何时串联 |
|---|---|
| write-tests | 用于回归测试规格 |
| review-migration | 在添加索引时 |
评论
支持 Markdown