Logo van Performance Optimization

Performance Optimization

Community
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

Overzicht

Uitgeverynulihao
RepositoryAgentSkillOS
Skillnaamperformance-optimization
Sterren
612
Forks
76
Meegeleverde bestanden
Alleen instructies
Links
  • Instructies in Markdown

    Het model laadt het bestand SKILL.md alleen als dat nodig is. Dat kost dus alleen tokens als een verzoek daadwerkelijk bij de skill past.

  • Werkt met elk LLM

    AI-skills bestaan uit instructies in gewone Markdown, niet uit aanbiederspecifieke code. Daardoor werken ze met GPT, Claude, Gemini, Grok of een lokaal model.

  • Compleet zonder extra bestanden

    Alles wat het model nodig heeft, staat in de instructies — geen extra bestanden om te synchroniseren.

  • Open source

    Gepubliceerd door ynulihao op GitHub. Bekijk de bronbestanden voordat je de skill installeert.

Installatie

Installeer de AI-skill Performance Optimization in TypingMind om deze met elk LLM te gebruiken, of voeg de skill toe aan een andere agent die SKILL.md kan lezen.

1

Installeren in TypingMind

TypingMind installeert een skill rechtstreeks vanuit de GitHub-map. De app leest SKILL.md, bundelt de bijbehorende bestanden en slaat het resultaat lokaal op.

  1. Open de app en ga naar Plug-ins → Skills.
  2. Kies "Installeren via GitHub".
  3. Plak de onderstaande URL van de skillmap en bevestig.
    https://github.com/ynulihao/AgentSkillOS/tree/main/data/skill_seeds/performance-optimization
  4. Schakel de skill in voor elke chat waarin je de skill wilt kunnen gebruiken.
Plug-ins → Skills → Skill toevoegen → Via GitHub-URL. Plak vervolgens de map-URL en druk op Doorgaan.
2

Installeren in een andere agent

Elke agent die het Agent Skills-formaat kan lezen, kan deze skill gebruiken — kopieer de map naar de skillmap van die agent.

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
Start Claude Code na het kopiëren opnieuw op, zodat de nieuwe skill wordt herkend.

Gebruik deze skill in TypingMind

Schakel Performance Optimization in voor een chat naar keuze in TypingMind en het model doet de rest. De naam en beschrijving staan in de systeemprompt. Zodra een verzoek bij de skill past, laadt het model zelf de volledige instructies. Je hoeft de skill nooit handmatig aan te roepen. Pas als het model de skill daadwerkelijk gebruikt, kost dat tokens.

Het model laadt Performance Optimization automatisch zodra een verzoek erbij past.

Werkt met elk AI-model

AI-skills zijn gewone Markdown-instructies in plaats van aanbiederspecifieke code. Daardoor is Performance Optimization niet gebonden aan het model waarvoor de skill is geschreven. Installeer de skill één keer in TypingMind en gebruik deze met GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama of een lokaal model dat je zelf draait — allemaal met je eigen API-sleutels.

  • Alleen geladen wanneer nodig

    De systeemprompt bevat alleen de naam en beschrijving. De instructies worden bij het eerste bijpassende verzoek opgehaald, dus een ongebruikte skill kost niets.

  • Wissel van model tijdens een chat

    Omdat de skill uit instructies bestaat en niet uit code, blijft deze werken als je van model wisselt — het volgende model leest hetzelfde SKILL.md-bestand.

Skillinstructies

Dit is de inhoud van SKILL.md die het model laadt. Lees deze vóór de installatie — een skill bestaat uit instructies die je model zal volgen.

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

Veelgestelde vragen

Wat doet de AI-skill 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.

Waarom Performance Optimization gebruiken in TypingMind?

Omdat je deze skill één keer installeert en met elk model kunt gebruiken. Performance Optimization bestaat uit gewone Markdown in plaats van aanbiederspecifieke code. Dezelfde skill werkt dus met GPT-5, Claude, Gemini, Grok of een lokaal model. Ook als je midden in een chat van model wisselt, blijft de skill werken. TypingMind werkt met je eigen API-sleutels, dus je betaalt aanbieders rechtstreeks in plaats van een abonnement per gebruikersplek af te sluiten. Je skills en chats blijven in je eigen opslag.

Hoe installeer ik Performance Optimization in TypingMind?

Open Plug-ins → Skills → Installeren vanaf GitHub in TypingMind en plak https://github.com/ynulihao/AgentSkillOS/tree/main/data/skill_seeds/performance-optimization. TypingMind leest het bestand SKILL.md en installeert het als een skill die je per chat kunt inschakelen.

Welke AI-modellen kunnen Performance Optimization gebruiken?

Elk model dat je in TypingMind koppelt. AI-skills bestaan uit gewone Markdown-instructies in plaats van aanbiederspecifieke code. GPT, Claude, Gemini, Grok en lokale modellen kunnen deze skill dus allemaal laden wanneer een verzoek erbij past.

Hoeveel AI-modellen kan ik met Performance Optimization gebruiken?

Zoveel als je wilt. Je kunt Performance Optimization gebruiken met elk model dat skills ondersteunt, zoals GPT, Claude, Gemini, Grok, DeepSeek, Mistral of Llama. Allemaal in TypingMind met je eigen API-sleutels.

Is de AI-skill Performance Optimization gratis?

Deze skill is door ynulihao op GitHub gepubliceerd. Bekijk de repository voor de licentievoorwaarden. Je betaalt alleen je eigen AI-aanbieder voor de tokens die je gebruikt.

Wat zijn AI-skills?

Een AI-skill is een herbruikbare bundel instructies die een AI-model leert hoe het één specifieke taak moet uitvoeren. De skill volgt het open Agent Skills-formaat: het bestand SKILL.md bevat de naam en beschrijving van de skill. Daarnaast kan de skill scripts, sjablonen of referentiebestanden bevatten die het model nodig heeft. Het model leest de instructies alleen als je verzoek bij de skill past. Een geïnstalleerde skill kost dus niets zolang deze niet wordt gebruikt.

Waarin verschillen AI-skills van plug-ins of MCP-servers?

Een plug-in of MCP-server geeft een model nieuwe tools om aan te roepen: code die ergens wordt uitgevoerd en een resultaat teruggeeft. Een AI-skill geeft het model juist kennis en een werkwijze: hoe het een taak moet aanpakken, welke stappen het moet volgen en hoe goede uitvoer eruitziet. Skills bestaan uit gewone Markdown en hebben dus geen server, API-sleutel of runtime nodig. Ze werken met elk model.

Bekijk alles

Maak nu je eigen AI-werkruimte

Schrijf je in voor onze nieuwsbrief en blijf op de hoogte van nieuwe functies en toekomstige weggeefacties 👇