Code Optimizer 标志

Code Optimizer

社区
ArabelaTso
code-optimizer

分析并优化代码,提升性能、降低内存占用并提高效率。代码运行缓慢、占用内存过多或效率低下时使用。支持 Python 和 Java 优化,包括提升执行速度、减少内存占用、优化数据库查询和提高 I/O 效率。提供优化前后的示例,详细解释优化生效的原因,分析复杂度,并展示可量化的性能提升。

Add to TypingMind

概览

发布者ArabelaTso
代码仓库Skills-4-SE
技能名称code-optimizer
星标数
258
复刻数
25
附带文件
仅含指令
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 ArabelaTso 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Code Optimizer AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/ArabelaTso/Skills-4-SE/tree/main/skills/code-optimizer
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE.git /tmp/Skills-4-SE
mkdir -p .claude/skills
cp -r /tmp/Skills-4-SE/skills/code-optimizer .claude/skills/code-optimizer
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Code Optimizer,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Code Optimizer。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Code Optimizer 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Code Optimizer

Improve code performance, memory usage, and efficiency through systematic optimization.

Core Capabilities

This skill helps optimize code by:

  1. Analyzing performance bottlenecks - Identifying slow or inefficient code
  2. Suggesting optimizations - Providing concrete improvements with examples
  3. Explaining trade-offs - Describing benefits and potential drawbacks
  4. Measuring impact - Estimating performance gains
  5. Preserving correctness - Ensuring optimizations don't change behavior

Optimization Workflow

Step 1: Identify Optimization Opportunities

Analyze code to find performance bottlenecks.

Look for:

  • Nested loops (O(n²) or worse complexity)
  • Repeated expensive operations
  • Inefficient data structures
  • Unnecessary object creation
  • Database N+1 queries
  • Blocking I/O operations
  • Memory leaks or excessive allocation

Quick Analysis Questions:

  • What is the time complexity? Can it be reduced?
  • Are there repeated calculations that could be cached?
  • Is the right data structure being used?
  • Are there unnecessary copies or allocations?
  • Can operations be batched or parallelized?

Step 2: Categorize the Optimization

Determine the type of optimization needed.

Execution Speed:

  • Algorithm optimization (better complexity)
  • Loop optimization
  • Caching/memoization
  • Lazy evaluation
  • Parallel processing

Memory Usage:

  • Reduce object creation
  • Use generators/streams instead of lists
  • Clear references to enable garbage collection
  • Use appropriate data structures
  • Avoid memory leaks

Database Operations:

  • Query optimization (indexes, joins)
  • Batch operations
  • Connection pooling
  • Caching
  • Reduce round trips

I/O Operations:

  • Buffering
  • Async/non-blocking I/O
  • Batch requests
  • Compression
  • Caching

Step 3: Propose Optimization with Examples

Provide before/after code with clear explanations.

Optimization Template:

markdown
## Optimization: [Brief Description]

### Before (Inefficient)
```[language]
[original code]

Issues:

  • Issue 1: [Problem description]
  • Issue 2: [Problem description]

Complexity: O([complexity]) Performance: [estimated time/memory]

After (Optimized)

[optimized code]

Improvements:

  • Improvement 1: [What changed]
  • Improvement 2: [What changed]

Complexity: O([new complexity]) Performance: [estimated time/memory] Gain: [X% faster / Y% less memory]

Why This Works

[Detailed explanation of the optimization]

Trade-offs

Pros:

  • [Benefit 1]
  • [Benefit 2]

Cons:

  • [Drawback 1, if any]
  • [Drawback 2, if any]

When to Use

  • Use when: [scenario]
  • Avoid when: [scenario]

### Step 4: Measure and Validate

Ensure optimization actually improves performance.

**Measurement Techniques:**

**Python:**
```python
import time
import memory_profiler

# Time measurement
start = time.time()
result = function()
elapsed = time.time() - start
print(f"Elapsed: {elapsed:.4f}s")

# Memory measurement
from memory_profiler import profile

@profile
def function():
    # Code to profile
    pass

Java:

java
// Time measurement
long start = System.nanoTime();
result = function();
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed: " + elapsed / 1_000_000 + "ms");

// Memory measurement
Runtime runtime = Runtime.getRuntime();
long before = runtime.totalMemory() - runtime.freeMemory();
result = function();
long after = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory used: " + (after - before) / 1024 + "KB");

Validation Checklist:

  • ✓ Correctness: Output matches original
  • ✓ Performance: Measurable improvement
  • ✓ Memory: Reduced allocation or leaks fixed
  • ✓ Maintainability: Code remains readable
  • ✓ Edge cases: Handles all inputs correctly

Common Optimizations

Python Optimizations

1. Use List Comprehensions Over Loops
python
# Before: O(n) with overhead
numbers = []
for i in range(1000):
    if i % 2 == 0:
        numbers.append(i * 2)

# After: O(n) faster execution
numbers = [i * 2 for i in range(1000) if i % 2 == 0]

# Gain: 2-3x faster
2. Use Generators for Large Sequences
python
# Before: O(n) memory
def get_numbers(n):
    result = []
    for i in range(n):
        result.append(i ** 2)
    return result

numbers = get_numbers(1000000)  # Uses ~8MB memory

# After: O(1) memory
def get_numbers(n):
    for i in range(n):
        yield i ** 2

numbers = get_numbers(1000000)  # Uses minimal memory

# Gain: 99% less memory for large n
3. Use Built-in Functions
python
# Before: Slower
total = 0
for num in numbers:
    total += num

# After: Faster (C implementation)
total = sum(numbers)

# Gain: 10-20x faster for large lists
4. Avoid Repeated Lookups
python
# Before: Repeated lookups
for i in range(len(data)):
    process(data[i])

# After: Single lookup
for item in data:
    process(item)

# Or with enumerate
for i, item in enumerate(data):
    process(item)

# Gain: Faster iteration, more Pythonic
5. Use Sets for Membership Testing
python
# Before: O(n) per lookup
items = [1, 2, 3, 4, 5, ...]  # Large list
if x in items:  # O(n) lookup
    do_something()

# After: O(1) per lookup
items = {1, 2, 3, 4, 5, ...}  # Set
if x in items:  # O(1) lookup
    do_something()

# Gain: 100x faster for large collections

See references/python_optimizations.md for comprehensive Python optimization patterns.

Java Optimizations

1. Use StringBuilder for String Concatenation
java
// Before: O(n²) - creates n strings
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i + ",";  // Creates new string each time
}

// After: O(n) - single buffer
StringBuilder result = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    result.append(i).append(",");
}
String output = result.toString();

// Gain: 100x faster for large loops
2. Use Appropriate Collection Types
java
// Before: Wrong data structure
List<Integer> numbers = new ArrayList<>();
numbers.contains(42);  // O(n) lookup

// After: Right data structure
Set<Integer> numbers = new HashSet<>();
numbers.contains(42);  // O(1) lookup

// Gain: 1000x faster for large collections
3. Avoid Unnecessary Object Creation
java
// Before: Creates objects in loop
for (int i = 0; i < 1000; i++) {
    String key = new String("key" + i);  // Unnecessary
    map.put(key, value);
}

// After: Reuse or use literals
for (int i = 0; i < 1000; i++) {
    String key = "key" + i;  // String interning
    map.put(key, value);
}

// Gain: Less GC pressure, faster
4. Use Primitive Collections
java
// Before: Autoboxing overhead
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
    numbers.add(i);  // Boxing int to Integer
}

// After: Primitive arrays or specialized libraries
int[] numbers = new int[1000000];
for (int i = 0; i < 1000000; i++) {
    numbers[i] = i;  // No boxing
}

// Or use TIntArrayList from Trove
TIntArrayList numbers = new TIntArrayList();

// Gain: 50% less memory, faster access

See references/java_optimizations.md for comprehensive Java optimization patterns.

Database Optimizations

1. Fix N+1 Query Problem
python
# Before: N+1 queries
users = User.query.all()  # 1 query
for user in users:
    posts = user.posts.all()  # N queries
    process(posts)

# After: Single query with join
users = User.query.options(
    joinedload(User.posts)
).all()  # 1 query
for user in users:
    posts = user.posts  # Already loaded
    process(posts)

# Gain: 100x faster for large datasets
2. Add Indexes
sql
-- Before: Full table scan O(n)
SELECT * FROM users WHERE email = 'user@example.com';

-- After: Index lookup O(log n)
CREATE INDEX idx_users_email ON users(email);
SELECT * FROM users WHERE email = 'user@example.com';

-- Gain: 1000x faster for large tables
3. Batch Operations
python
# Before: N round trips
for item in items:
    db.execute("INSERT INTO table VALUES (?)", (item,))
    db.commit()

# After: Single batch
db.executemany("INSERT INTO table VALUES (?)",
               [(item,) for item in items])
db.commit()

# Gain: 10-100x faster

See references/database_optimizations.md for comprehensive database optimization patterns.

I/O Optimizations

1. Use Buffered I/O
python
# Before: Unbuffered (many system calls)
with open('file.txt', 'r') as f:
    for line in f:
        process(line.strip())

# After: Buffered reading
with open('file.txt', 'r', buffering=8192) as f:
    for line in f:
        process(line.strip())

# Gain: 10x faster for small lines
2. Batch API Calls
python
# Before: N API calls
for user_id in user_ids:
    user = api.get_user(user_id)  # 100 calls
    process(user)

# After: Batch API call
users = api.get_users_batch(user_ids)  # 1 call
for user in users:
    process(user)

# Gain: 100x faster (network latency)

Optimization Process

1. Profile Before Optimizing

Python Profiling:

bash
# Time profiling
python -m cProfile -s cumulative script.py

# Line-by-line profiling
pip install line_profiler
kernprof -l -v script.py

# Memory profiling
pip install memory_profiler
python -m memory_profiler script.py

Java Profiling:

bash
# JVM profiling with VisualVM
jvisualvm

# Or Java Flight Recorder
java -XX:+UnlockCommercialFeatures -XX:+FlightRecorder \
     -XX:StartFlightRecording=duration=60s,filename=recording.jfr \
     MyApp

2. Focus on Hot Paths

Optimize the 20% of code that takes 80% of time.

Find Hot Paths:

  • Profile to find slowest functions
  • Measure actual execution time
  • Focus on code executed frequently
  • Ignore code executed rarely

3. Measure Impact

Compare before and after:

python
import timeit

# Before
before = timeit.timeit(
    'old_function(data)',
    setup='from module import old_function, data',
    number=1000
)

# After
after = timeit.timeit(
    'new_function(data)',
    setup='from module import new_function, data',
    number=1000
)

improvement = (before - after) / before * 100
print(f"Improvement: {improvement:.1f}%")

4. Maintain Readability

Don't sacrifice code clarity for minor gains.

Good Optimization:

python
# Clear and fast
users = [u for u in all_users if u.is_active]

Bad Optimization:

python
# Obscure for minimal gain
users = list(filter(lambda u: u.is_active, all_users))

Best Practices

  1. Profile first - Don't guess, measure
  2. Focus on bottlenecks - Optimize hot paths only
  3. Preserve correctness - Test thoroughly after optimizing
  4. Document trade-offs - Explain why optimization is worth it
  5. Measure improvements - Quantify performance gains
  6. Consider maintainability - Don't make code unreadable
  7. Use appropriate tools - Profilers, benchmarks, load tests
  8. Think about complexity - O(n²) to O(n log n) matters more than micro-optimizations
  9. Cache wisely - Balance memory vs. computation
  10. Avoid premature optimization - Optimize when proven necessary

Resources

  • references/python_optimizations.md - Comprehensive Python optimization techniques and patterns
  • references/java_optimizations.md - Comprehensive Java optimization techniques and patterns
  • references/database_optimizations.md - Database query and schema optimization strategies

Quick Reference

Optimization TypePythonJavaImpact
Algorithm complexityUse better algorithmUse better algorithmHigh
Data structuresset/dict for lookupHashMap/HashSetHigh
String buildingjoin() or f-stringsStringBuilderHigh
GeneratorsyieldStream APIMedium (memory)
Caching@lru_cacheConcurrentHashMapMedium-High
BatchingBatch DB/API callsBatch operationsHigh
IndexingUse dict/setAdd DB indexesHigh
Lazy evaluationGeneratorsStreams/SuppliersMedium

常见问题

Code Optimizer AI 技能有什么作用?

分析并优化代码,提升性能、降低内存占用并提高效率。代码运行缓慢、占用内存过多或效率低下时使用。支持 Python 和 Java 优化,包括提升执行速度、减少内存占用、优化数据库查询和提高 I/O 效率。提供优化前后的示例,详细解释优化生效的原因,分析复杂度,并展示可量化的性能提升。

为什么在 TypingMind 中使用 Code Optimizer?

因为您只需安装一次,就能搭配任何模型使用。Code Optimizer 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Code Optimizer?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/ArabelaTso/Skills-4-SE/tree/main/skills/code-optimizer。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Code Optimizer?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Code Optimizer 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Code Optimizer 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Code Optimizer AI 技能免费吗?

是的。ArabelaTso 已在 GitHub 上根据 Apache-2.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇