/vibe:universal-performance-optimizationfrom vibe
Provides language-agnostic performance optimization best practices covering frontend, backend, database, network, caching, concurrency, and infrastructure. Includes checklists, anti-patterns, and troubleshooting guidance.
Ships in vibe. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Performance is the difference between a product users love and one they abandon. This guide provides comprehensive, language-agnostic performance optimization practices covering all layers of modern software systems. Whether you're optimizing a web app, API, database, or distributed system, these principles and techniques will help you build fast, efficient, and scalable software.
Key Philosophy: Measure first, optimize second. Never guess—always profile, benchmark, and validate improvements with data.
| Metric | Target | Maximum |
|---|---|---|
| Time to First Byte (TTFB) | < 200ms | < 600ms |
| First Contentful Paint (FCP) | < 1.8s | < 3.0s |
| Largest Contentful Paint (LCP) | < 2.5s | < 4.0s |
| Time to Interactive (TTI) | < 3.8s | < 7.3s |
| Cumulative Layout Shift (CLS) | < 0.1 | < 0.25 |
| First Input Delay (FID) | < 100ms | < 300ms |
| API Response Time (p95) | < 200ms | < 1000ms |
| Database Query Time (p95) | < 50ms | < 200ms |
// ❌ BAD: Layout thrashing
for (let i = 0; i < elements.length; i++) {
elements[i].style.width = box.offsetWidth + "px"; // Read/write interleaved
}
// ✅ GOOD: Batch reads and writes
const width = box.offsetWidth;
for (let i = 0; i < elements.length; i++) {
elements[i].style.width = width + "px";
}
box-shadow, border-radius, opacity, transform can be costly.contain: layout|paint|size for isolated components.transform and opacity for GPU-accelerated animations./* ❌ BAD: Complex selector */
div.container > ul li:nth-child(2n) a.link:hover {
}
/* ✅ GOOD: Simple, specific selector */
.link-hover {
}
// ❌ BAD: Triggers on every keystroke
input.addEventListener("input", (e) => {
expensiveAPICall(e.target.value);
});
// ✅ GOOD: Debounced API call
const debouncedCall = debounce((value) => {
expensiveAPICall(value);
}, 300);
input.addEventListener("input", (e) => {
debouncedCall(e.target.value);
});
srcset and sizes attributes.loading="lazy" for below-the-fold images.<!-- ✅ GOOD: Responsive, lazy-loaded, modern format -->
<picture>
<source srcset="image.avif" type="image/avif" />
<source srcset="image.webp" type="image/webp" />
<img
src="image.jpg"
srcset="image-320w.jpg 320w, image-640w.jpg 640w, image-1280w.jpg 1280w"
sizes="(max-width: 320px) 280px, (max-width: 640px) 600px, 1200px"
loading="lazy"
width="1200"
height="800"
alt="Description"
/>
</picture>
font-display: swap to avoid FOIT (Flash of Invisible Text).<link rel="preload" as="font">/* ✅ GOOD: System font stack */
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
/* ✅ GOOD: Custom font with swap */
@font-face {
font-family: "CustomFont";
src: url("custom-font.woff2") format("woff2");
font-display: swap;
unicode-range: U+0020-007F; /* Basic Latin only */
}
// ✅ GOOD: Dynamic import for route
const AdminPanel = () => import("./AdminPanel.vue");
// ✅ GOOD: Dynamic import with loading state
const heavyLibrary = async () => {
const module = await import("heavy-library");
return module.default;
};
React.memo, useMemo, useCallback to prevent re-renders.React.lazy() and <Suspense> for lazy loading.react-window or react-virtualized for long lists.useTransition and useDeferredValue for non-urgent updates.// ❌ BAD: Creates new function on every render
<Button onClick={() => handleClick(id)} />;
// ✅ GOOD: Memoized callback
const memoizedClick = useCallback(() => handleClick(id), [id]);
<Button onClick={memoizedClick} />;
// ✅ GOOD: Memoized expensive computation
const expensiveResult = useMemo(() => {
return computeExpensiveValue(input);
}, [input]);
v-show for frequent toggles (keeps DOM, toggles CSS).defineAsyncComponent for code splitting.v-for for efficient list updates.<!-- ✅ GOOD: Computed property for caching -->
<template>
<div>{{ expensiveComputation }}</div>
</template>
<script setup>
import { computed } from "vue";
const expensiveComputation = computed(() => {
return heavyCalculation(props.data);
});
</script>
*ngFor for efficient list rendering.// ✅ GOOD: OnPush change detection
@Component({
selector: 'app-item',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ItemComponent { }
// ✅ GOOD: TrackBy function
trackByFn(index: number, item: Item): number {
return item.id;
}
| Operation | Array | Hash Map | Binary Tree | Linked List |
|---|---|---|---|---|
| Access | O(1) | O(1) avg | O(log n) | O(n) |
| Search | O(n) | O(1) avg | O(log n) | O(n) |
| Insert | O(n) | O(1) avg | O(log n) | O(1) |
| Delete | O(n) | O(1) avg | O(log n) | O(1) |
# ❌ BAD: O(n²) nested loops
def find_duplicates_slow(arr):
duplicates = []
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] == arr[j]:
duplicates.append(arr[i])
return duplicates
# ✅ GOOD: O(n) with hash set
def find_duplicates_fast(arr):
seen = set()
duplicates = set()
for item in arr:
if item in seen:
duplicates.add(item)
seen.add(item)
return list(duplicates)
// ❌ BAD: Sequential API calls
async function fetchDataSlow(ids) {
const results = [];
for (const id of ids) {
const data = await fetch(`/api/data/${id}`);
results.push(data);
}
return results;
}
// ✅ GOOD: Parallel API calls
async function fetchDataFast(ids) {
const promises = ids.map((id) => fetch(`/api/data/${id}`));
return Promise.all(promises);
}
# ✅ GOOD: Context manager ensures cleanup
with open('file.txt', 'r') as f:
data = f.read()
# File automatically closed
# ✅ GOOD: Connection pooling
from sqlalchemy import create_engine, pool
engine = create_engine(
'postgresql://user:pass@host/db',
poolclass=pool.QueuePool,
pool_size=10,
max_overflow=20
)
-- ❌ BAD: Missing index on frequently queried column
SELECT * FROM users WHERE email = '[email protected]';
-- ✅ GOOD: Create index on email
CREATE INDEX idx_users_email ON users(email);
-- ✅ GOOD: Composite index for common query pattern
CREATE INDEX idx_orders_user_date ON orders(user_id, order_date DESC);
-- ✅ GOOD: Covering index includes all needed columns
CREATE INDEX idx_users_email_name ON users(email) INCLUDE (first_name, last_name);
-- ❌ BAD: SELECT * fetches unnecessary data
SELECT * FROM users WHERE active = true;
-- ✅ GOOD: Select only needed columns
SELECT id, email, name FROM users WHERE active = true;
-- ❌ BAD: N+1 query problem
SELECT * FROM posts;
-- Then for each post:
SELECT * FROM users WHERE id = post.author_id;
-- ✅ GOOD: Single query with JOIN
SELECT posts.*, users.name
FROM posts
JOIN users ON posts.author_id = users.id;
-- ✅ GOOD: Use appropriate data types
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE, -- Not TEXT
age SMALLINT, -- Not INTEGER
is_active BOOLEAN DEFAULT true, -- Not CHAR(1)
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- ✅ GOOD: Partition large table
CREATE TABLE orders (
id BIGSERIAL,
order_date DATE NOT NULL,
amount DECIMAL(10,2)
) PARTITION BY RANGE (order_date);
CREATE TABLE orders_2024 PARTITION OF orders
FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
# ❌ BAD: Transaction per insert
for record in records:
db.execute("INSERT INTO table VALUES (?)", record)
db.commit()
# ✅ GOOD: Batch insert in single transaction
db.execute_many("INSERT INTO table VALUES (?)", records)
db.commit()
// ❌ BAD: Multiple round trips to database
for (const id of ids) {
await db.collection("users").findOne({ _id: id });
}
// ✅ GOOD: Single query with $in operator
await db
.collection("users")
.find({ _id: { $in: ids } })
.toArray();
Cache-Control, ETag, Last-Modified.✅ GOOD: Response headers for caching
Cache-Control: public, max-age=31536000, immutable
Content-Encoding: br
ETag: "abc123"
Vary: Accept-Encoding
// ✅ GOOD: Cursor-based pagination
GET /api/items?cursor=eyJpZCI6MTIzfQ&limit=20
// Response
{
"data": [...],
"pagination": {
"next_cursor": "eyJpZCI6MTQzfQ",
"has_more": true
}
}
?fields=id,name).// ❌ BAD: Large, verbose JSON
{
"user_identifier": 12345,
"user_email_address": "[email protected]",
"user_first_name": "John",
"user_last_name": "Doe"
}
// ✅ GOOD: Compact JSON
{
"id": 12345,
"email": "[email protected]",
"name": "John Doe"
}
// ❌ BAD: Memory leak from event listener
function setupListener() {
const button = document.getElementById("btn");
button.addEventListener("click", handleClick);
// Listener never removed
}
// ✅ GOOD: Cleanup event listener
function setupListener() {
const button = document.getElementById("btn");
const handler = () => handleClick();
button.addEventListener("click", handler);
return () => {
button.removeEventListener("click", handler);
};
}
# ✅ GOOD: Timeout for HTTP request
import requests
try:
response = requests.get('https://api.example.com', timeout=5)
except requests.Timeout:
# Handle timeout
pass
def get_user(user_id):
# Check cache first
cached = cache.get(f'user:{user_id}')
if cached:
return cached
# Cache miss - fetch from database
user = db.query('SELECT * FROM users WHERE id = ?', user_id)
# Store in cache with TTL
cache.set(f'user:{user_id}', user, ttl=3600)
return user
def update_user(user_id, data):
# Update database
db.execute('UPDATE users SET ... WHERE id = ?', user_id)
# Update cache immediately
cache.set(f'user:{user_id}', data, ttl=3600)
def update_user(user_id, data):
# Update cache immediately
cache.set(f'user:{user_id}', data, ttl=3600)
# Queue database write asynchronously
queue.enqueue('db_write', user_id, data)
# ✅ GOOD: Cache stampede protection
def get_expensive_data(key):
cached = cache.get(key)
if cached:
return cached
# Acquire lock to prevent multiple fetches
lock_key = f'lock:{key}'
if cache.add(lock_key, 1, ttl=10): # Returns false if key exists
try:
data = expensive_computation()
cache.set(key, data, ttl=300)
return data
finally:
cache.delete(lock_key)
else:
# Another process is computing, wait and retry
time.sleep(0.1)
return get_expensive_data(key)
// ✅ GOOD: Parallel async operations
async function fetchUserData(userId) {
const [user, posts, comments] = await Promise.all([fetchUser(userId), fetchPosts(userId), fetchComments(userId)]);
return { user, posts, comments };
}
# ✅ GOOD: Thread-safe counter with lock
from threading import Lock
class Counter:
def __init__(self):
self.value = 0
self.lock = Lock()
def increment(self):
with self.lock:
self.value += 1
# ✅ GOOD: Process pool for CPU-bound work
from concurrent.futures import ProcessPoolExecutor
def cpu_intensive_task(data):
# Heavy computation
return result
with ProcessPoolExecutor(max_workers=4) as executor:
results = executor.map(cpu_intensive_task, data_list)
list, dict, set are highly optimized in C.cProfile, line_profiler, py-spy.# ❌ BAD: Slow list building
result = []
for i in range(1000):
result.append(i ** 2)
# ✅ GOOD: Fast list comprehension
result = [i ** 2 for i in range(1000)]
# ✅ BETTER: Generator for memory efficiency
result = (i ** 2 for i in range(1000))
arguments, eval, with.// ✅ GOOD: Stream large file
const fs = require("fs");
const stream = fs.createReadStream("large-file.txt");
stream.on("data", (chunk) => {
processChunk(chunk);
});
ArrayList, HashMap, avoid Vector, Hashtable.ExecutorService for concurrency.-Xmx, -Xms), GC algorithm (-XX:+UseG1GC).// ❌ BAD: String concatenation in loop
String result = "";
for (int i = 0; i < 1000; i++) {
result += i; // Creates new string each time
}
// ✅ GOOD: Use StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String result = sb.toString();
defer for resource cleanup.pprof for CPU and memory profiling.// ✅ GOOD: Worker pool pattern
func processItems(items []Item) {
jobs := make(chan Item, 100)
results := make(chan Result, 100)
// Start workers
for w := 0; w < 10; w++ {
go worker(jobs, results)
}
// Send jobs
for _, item := range items {
jobs <- item
}
close(jobs)
// Collect results
for i := 0; i < len(items); i++ {
<-results
}
}
cargo flamegraph, perf.// ✅ GOOD: Parallel iteration with Rayon
use rayon::prelude::*;
let results: Vec<_> = data.par_iter()
.map(|item| expensive_computation(item))
.collect();
# ✅ GOOD: Multi-stage build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/index.js"]
# ✅ GOOD: Resource limits and HPA
apiVersion: apps/v1
kind: Deployment
spec:
replicas: 3
template:
spec:
containers:
- name: app
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
spec:
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
// ✅ GOOD: Reuse connections in Lambda
const AWS = require("aws-sdk");
const dynamoDB = new AWS.DynamoDB.DocumentClient(); // Outside handler
exports.handler = async (event) => {
// Handler code reuses dynamoDB client
const result = await dynamoDB.get(params).promise();
return result;
};
// ✅ GOOD: Lazy loading images
func loadImage(url: URL, into imageView: UIImageView) {
imageView.image = placeholderImage
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url),
let image = UIImage(data: data) {
DispatchQueue.main.async {
imageView.image = image
}
}
}
}
# ✅ GOOD: Efficient password hashing
import bcrypt
# Hash password (slow by design)
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
# Verify password (also slow)
if bcrypt.checkpw(password.encode(), hashed):
# Password correct
pass
// ✅ GOOD: k6 load test script
import http from "k6/http";
import { check, sleep } from "k6";
export const options = {
stages: [
{ duration: "2m", target: 100 }, // Ramp up
{ duration: "5m", target: 100 }, // Stay at 100 users
{ duration: "2m", target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ["p(95)<500"], // 95% of requests under 500ms
},
};
export default function () {
const res = http.get("https://api.example.com/users");
check(res, {
"status is 200": (r) => r.status === 200,
"response time < 500ms": (r) => r.timings.duration < 500,
});
sleep(1);
}
| Language | CPU Profiler | Memory Profiler | Flame Graph |
|---|---|---|---|
| Python | cProfile, py-spy | memory_profiler | py-spy |
| Node.js | --prof, clinic | heapdump, clinic | 0x, clinic |
| Java | VisualVM, JProfiler | VisualVM, MAT | async-profiler |
| Go | pprof | pprof | pprof |
| Rust | perf, cargo-flamegraph | valgrind | cargo-flamegraph |
| .NET | dotTrace, PerfView | dotMemory | PerfView |
defer/asyncSet budgets and enforce with CI/CD:
{
"budgets": [
{
"path": "/",
"resourceSizes": [
{ "resourceType": "script", "budget": 200 },
{ "resourceType": "image", "budget": 500 },
{ "resourceType": "total", "budget": 1000 }
],
"resourceCounts": [
{ "resourceType": "script", "budget": 10 },
{ "resourceType": "third-party", "budget": 5 }
]
}
]
}
Performance optimization is a continuous process, not a one-time task. Always:
Remember: Premature optimization is the root of all evil, but late optimization is the root of all evil too. Find the balance.
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."
— Donald Knuth
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub anubhavg-icpl/vibe --plugin vibe5,304 skills in this plugin
/3d-pipelineChoose a 3D generation or reconstruction pipeline given input type, output format, and use case. Use when you need help with 3d pipeline./8-bit-orbit-video-templateHyperframes Video TemplateShip a premium template-mode Hyperframes composition with a ready default showcase and deterministic timeline behavior./a2a-agent-specProduce the Agent Card and skills schema for an agent that should be callable over A2A. Use when you need help with a2a agent spec.Other plugins' skills for the same job