Logo Performance Optimization

Performance Optimization

Cộng đồng
ynulihao
performance-optimization

Apply systematic performance optimization techniques when writing or reviewing code. Use when optimizing hot paths, reducing latency, improving throughput, fixing performance regressions, or when the user mentions performance, optimization, speed, latency, throughput, profiling, or benchmarking.

Add to TypingMind

Tổng quan

Nhà phát hànhynulihao
Kho mãAgentSkillOS
Tên kỹ năngperformance-optimization
Sao
612
Bản fork
76
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được ynulihao công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Performance Optimization trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/ynulihao/AgentSkillOS/tree/main/data/skill_seeds/performance-optimization
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ynulihao/AgentSkillOS.git /tmp/AgentSkillOS
mkdir -p .claude/skills
cp -r /tmp/AgentSkillOS/data/skill_seeds/performance-optimization .claude/skills/performance-optimization
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Performance Optimization trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Performance Optimization ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Performance Optimization với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Performance Optimization Skill

Apply these principles when optimizing code for performance. Focus on the critical 3% where performance truly matters - a 12% improvement is never marginal in engineering.

Core Philosophy

  1. Measure First: Never optimize without profiling data
  2. Estimate Costs: Back-of-envelope calculations before implementation
  3. Avoid Work: The fastest code is code that doesn't run
  4. Reduce Allocations: Memory allocation is often the hidden bottleneck
  5. Cache Locality: Memory access patterns dominate modern performance

Reference Latency Numbers

Use these for back-of-envelope calculations:

OperationLatency
L1 cache reference0.5 ns
Branch mispredict5 ns
L2 cache reference7 ns
Mutex lock/unlock25 ns
Main memory reference100 ns
Compress 1KB (Snappy)3 us
SSD random read (4KB)20 us
Round trip in datacenter50 us
Disk seek5 ms

Optimization Techniques (Priority Order)

1. Algorithmic Improvements (Highest Impact)

Always check algorithm complexity first:

O(N^2) → O(N log N)  = 1000x faster for N=1M
O(N)   → O(1)        = unbounded improvement

Common patterns:

  • Replace nested loops with hash lookups
  • Use sorted-list intersection → hash table lookups
  • Process in reverse post-order to eliminate per-element checks
  • Replace interval trees (O(log N)) with hash maps (O(1)) when ranges aren't needed

2. Reduce Memory Allocations

Allocation is expensive (~25-100ns + GC pressure)

python
# BAD: Allocates on every call
def process(items):
    result = []  # New allocation
    for item in items:
        result.append(transform(item))
    return result

# GOOD: Pre-allocate or reuse
def process(items, out=None):
    if out is None:
        out = [None] * len(items)
    for i, item in enumerate(items):
        out[i] = transform(item)
    return out

Techniques:

  • Pre-size containers with reserve() or known capacity
  • Hoist temporary containers outside loops
  • Reuse buffers across iterations (clear instead of recreate)
  • Move instead of copy large structures
  • Use stack allocation for bounded-lifetime objects

3. Compact Data Structures

Minimize memory footprint and cache lines touched:

rust
// BAD: 24 bytes due to padding
struct Item {
    flag: bool,      // 1 byte + 7 padding
    value: i64,      // 8 bytes
    count: i32,      // 4 bytes + 4 padding
}

// GOOD: 16 bytes with reordering
struct Item {
    value: i64,      // 8 bytes
    count: i32,      // 4 bytes
    flag: bool,      // 1 byte + 3 padding
}

Techniques:

  • Reorder struct fields by size (largest first)
  • Use smaller numeric types when range permits (u8 vs i32)
  • Replace 64-bit pointers with 32-bit indices
  • Keep hot fields together, move cold fields to separate struct
  • Use bit vectors for small-domain sets
  • Flatten nested maps: Map<A, Map<B, C>> → Map<(A,B), C>

4. Fast Paths for Common Cases

Optimize the common case without hurting rare cases:

python
# BAD: Always takes slow path
def parse_varint(data):
    return generic_varint_parser(data)

# GOOD: Fast path for common 1-byte case
def parse_varint(data):
    if data[0] < 128:  # Single byte - 90% of cases
        return data[0], 1
    return generic_varint_parser(data)  # Rare multi-byte

Techniques:

  • Handle common dimensions inline (1-D, 2-D tensors)
  • Check for empty/trivial inputs early
  • Specialize for common sizes (small strings, few elements)
  • Process trailing elements separately to avoid slow generic code

5. Precompute Expensive Information

Trade memory for compute when beneficial:

python
# BAD: Recomputes on every access
def is_vowel(char):
    return char.lower() in 'aeiou'

# GOOD: Lookup table
VOWEL_TABLE = [c.lower() in 'aeiou' for c in (chr(i) for i in range(256))]
def is_vowel(char):
    return VOWEL_TABLE[ord(char)]

Techniques:

  • Precompute flags/properties at construction time
  • Build lookup tables for character classification
  • Cache expensive computed properties
  • Validate at boundaries once, not repeatedly inside

6. Bulk/Batch APIs

Amortize fixed costs across multiple operations:

python
# BAD: N round trips
for item in items:
    result = db.lookup(item)

# GOOD: 1 round trip
results = db.lookup_many(items)

Design APIs that support:

  • Batch lookups instead of individual fetches
  • Vectorized operations over loops
  • Streaming interfaces for large datasets

7. Avoid Unnecessary Work

python
# BAD: Always computes expensive value
def process(data, config):
    expensive = compute_expensive(data)  # Always runs
    if config.needs_expensive:
        use(expensive)

# GOOD: Defer until needed
def process(data, config):
    if config.needs_expensive:
        expensive = compute_expensive(data)  # Only when needed
        use(expensive)

Techniques:

  • Lazy evaluation for expensive operations
  • Short-circuit evaluation in conditions
  • Move loop-invariant code outside loops
  • Specialize instead of using general-purpose libraries in hot paths

8. Help the Compiler/Runtime

Lower-level optimizations when profiling shows need:

rust
// Avoid function call overhead in hot loops
#[inline(always)]
fn hot_function(x: i32) -> i32 { x * 2 }

// Copy to local variable for better alias analysis
fn process(data: &mut [i32], factor: &i32) {
    let f = *factor;  // Compiler knows this won't change
    for x in data {
        *x *= f;
    }
}

Techniques:

  • Use raw pointers/indices instead of iterators in critical loops
  • Hand-unroll very hot loops (4+ iterations)
  • Move slow-path code to separate non-inlined functions
  • Avoid abstractions that hide costs in hot paths

9. Reduce Synchronization

Minimize lock contention and atomic operations:

  • Default to thread-compatible (external sync) not thread-safe
  • Sample statistics (1-in-32) instead of tracking everything
  • Batch updates to shared state
  • Use thread-local storage for per-thread data

Profiling Workflow

  1. Identify hotspots: Use profiler (pprof, perf, py-spy)
  2. Measure baseline: Write benchmark before optimizing
  3. Estimate improvement: Calculate expected gain
  4. Implement change: Focus on one optimization at a time
  5. Verify improvement: Run benchmark, confirm gain
  6. Check for regressions: Ensure no other code paths slowed down

When Profile is Flat (No Clear Hotspots)

  • Pursue multiple small 1-2% improvements collectively
  • Look for restructuring opportunities higher in call stack
  • Profile allocations specifically (often hidden cost)
  • Gather hardware performance counters (cache misses, branch mispredicts)
  • Consider if the code is already well-optimized

Anti-Patterns to Avoid

  1. Premature optimization in non-critical code
  2. Optimizing without measurement - changes based on intuition
  3. Micro-optimizing while ignoring algorithmic complexity
  4. Copying when moving would suffice
  5. Growing containers one element at a time (quadratic)
  6. Allocating in loops when reuse is possible
  7. String formatting in hot paths (use pre-built templates)
  8. Regex when simple string matching suffices

Estimation Template

Before optimizing, estimate:

Operation cost: ___ ns/us/ms
Frequency: ___ times per second/request
Total time: cost × frequency = ___
Improvement target: ___% reduction
Expected new time: ___
Is this worth it? [ ] Yes [ ] No

Câu hỏi thường gặp

Kỹ năng AI Performance Optimization làm được gì?

Apply systematic performance optimization techniques when writing or reviewing code. Use when optimizing hot paths, reducing latency, improving throughput, fixing performance regressions, or when the user mentions performance, optimization, speed, latency, throughput, profiling, or benchmarking.

Vì sao nên dùng Performance Optimization trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Performance Optimization là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Performance Optimization trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/ynulihao/AgentSkillOS/tree/main/data/skill_seeds/performance-optimization. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Performance Optimization?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Performance Optimization với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Performance Optimization với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Performance Optimization có miễn phí không?

Kỹ năng này được ynulihao phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇