| name | performance-optimizer |
| description | Identifies and resolves performance bottlenecks in applications, APIs, and systems. Use when profiling slow code, optimizing algorithms, improving response times, reducing memory usage, implementing caching strategies, or analyzing system performance metrics. |
Performance Optimizer Skill
This skill helps identify and resolve performance issues across the application stack. Use this whenever you need to profile code, optimize algorithms, implement caching, or improve system throughput.
Performance Principles
1. Optimization Rules
- Don't optimize prematurely - Measure first, optimize second
- Profile before guessing - Data beats intuition
- Optimize the critical path - Focus on what matters most
- Consider trade-offs - Speed vs memory vs complexity
2. Performance Metrics
| Metric | Description | Target |
|---|
| Latency | Time to complete one operation | < 100ms (API) |
| Throughput | Operations per unit time | Depends on load |
| p50/p95/p99 | Percentile latencies | p99 < 2x p50 |
| TTFB | Time to first byte | < 200ms |
| Memory usage | RAM consumption | Within limits |
| CPU usage | Processor utilization | < 70% sustained |
3. Big O Quick Reference
| Complexity | Name | Example |
|---|
O(1) | Constant | Hash lookup, array access |
O(log n) | Logarithmic | Binary search |
O(n) | Linear | Array iteration |
O(n log n) | Linearithmic | Efficient sorting |
O(n²) | Quadratic | Nested loops |
O(2ⁿ) | Exponential | Recursive fibonacci |
Profiling Techniques
Python Profiling
import cProfile
import pstats
def profile_code():
profiler = cProfile.Profile()
profiler.enable()
result = expensive_function()
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20)
from line_profiler import profile
@profile
def slow_function():
result = []
for i in range(10000):
result.append(i ** 2)
return result
from memory_profiler import profile
@profile
def memory_hungry():
large_list = [i for i in range(1000000)]
return sum(large_list)
import time
from functools import wraps
def timing(f):
@wraps(f)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = f(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{f.__name__} took {elapsed:.4f} seconds")
return result
return wrapper
@timing
def my_function():
pass
JavaScript Profiling
console.time('operation');
expensiveOperation();
console.timeEnd('operation');
const start = performance.now();
expensiveOperation();
const end = performance.now();
console.log(`Execution time: ${end - start}ms`);
const timingMiddleware = (req, res, next) => {
const start = process.hrtime.bigint();
res.on('finish', () => {
const end = process.hrtime.bigint();
const duration = Number(end - start) / 1e6;
console.log(`${req.method} ${req.path} - ${duration.toFixed(2)}ms`);
});
next();
};
Database Query Profiling
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders
WHERE customer_id = 123
ORDER BY created_at DESC
LIMIT 10;
SET profiling = 1;
SELECT * FROM orders WHERE customer_id = 123;
SHOW PROFILE FOR QUERY 1;
Common Bottlenecks & Solutions
1. Algorithm Optimization
def find_duplicates_slow(items):
duplicates = []
for i, item in enumerate(items):
for j, other in enumerate(items):
if i != j and item == other and item not in duplicates:
duplicates.append(item)
return duplicates
def find_duplicates_fast(items):
seen = set()
duplicates = set()
for item in items:
if item in seen:
duplicates.add(item)
seen.add(item)
return list(duplicates)
def find_user_slow(users, user_id):
for user in users:
if user['id'] == user_id:
return user
return None
users_by_id = {user['id']: user for user in users}
def find_user_fast(user_id):
return users_by_id.get(user_id)
2. Loop Optimization
def process_items_slow(items):
results = []
for item in items:
config = load_config()
result = process(item, config)
results.append(result)
return results
def process_items_fast(items):
config = load_config()
results = []
for item in items:
result = process(item, config)
results.append(result)
return results
def build_string_slow(items):
result = ""
for item in items:
result += str(item) + ", "
return result
def build_string_fast(items):
return ", ".join(str(item) for item in items)
def squares_slow(n):
result = []
for i in range(n):
result.append(i ** 2)
return result
def squares_fast(n):
return [i ** 2 for i in range(n)]
3. I/O Optimization
import requests
def fetch_all_slow(urls):
results = []
for url in urls:
response = requests.get(url)
results.append(response.json())
return results
import aiohttp
import asyncio
async def fetch_all_fast(urls):
async with aiohttp.ClientSession() as session:
tasks = [fetch_one(session, url) for url in urls]
return await asyncio.gather(*tasks)
async def fetch_one(session, url):
async with session.get(url) as response:
return await response.json()
def read_slow(filename):
with open(filename) as f:
lines = f.readlines()
return [process(line) for line in lines]
def read_fast(filename):
with open(filename) as f:
for line in f:
yield process(line)
4. Memory Optimization
def process_large_file_slow(filename):
results = []
with open(filename) as f:
for line in f:
results.append(transform(line))
return results
def process_large_file_fast(filename):
with open(filename) as f:
for line in f:
yield transform(line)
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Point:
__slots__ = ['x', 'y', 'z']
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: float
y: float
z: float
def create_many_dicts():
return [{'x': i, 'y': i*2} for i in range(1000000)]
import numpy as np
def create_array():
return np.array([[i, i*2] for i in range(1000000)])
Caching Strategies
In-Memory Caching
from functools import lru_cache
from cachetools import TTLCache, LRUCache
import time
@lru_cache(maxsize=1000)
def expensive_computation(n):
time.sleep(1)
return n ** 2
cache = TTLCache(maxsize=100, ttl=300)
def get_user(user_id):
if user_id in cache:
return cache[user_id]
user = db.fetch_user(user_id)
cache[user_id] = user
return user
class SimpleCache:
def __init__(self, ttl_seconds=300):
self.cache = {}
self.ttl = ttl_seconds
def get(self, key):
if key in self.cache:
value, expiry = self.cache[key]
if time.time() < expiry:
return value
del self.cache[key]
return None
def set(self, key, value):
self.cache[key] = (value, time.time() + self.ttl)
def invalidate(self, key):
self.cache.pop(key, None)
Redis Caching
import redis
import json
from functools import wraps
redis_client = redis.Redis(host='localhost', port=6379, db=0)
def cache_result(ttl=300):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
key = f"{func.__name__}:{hash(str(args) + str(kwargs))}"
cached = redis_client.get(key)
if cached:
return json.loads(cached)
result = func(*args, **kwargs)
redis_client.setex(key, ttl, json.dumps(result))
return result
return wrapper
return decorator
@cache_result(ttl=600)
def get_product_details(product_id):
return db.query_product(product_id)
def update_product(product_id, data):
db.update_product(product_id, data)
redis_client.delete(f"get_product_details:{hash(str((product_id,)))}")
for key in redis_client.scan_iter(f"product:{product_id}:*"):
redis_client.delete(key)
class CacheAside:
def __init__(self, cache, db):
self.cache = cache
self.db = db
def read(self, key):
value = self.cache.get(key)
if value:
return value
value = self.db.get(key)
if value:
self.cache.set(key, value)
return value
def write(self, key, value):
self.db.set(key, value)
self.cache.set(key, value)
self.cache.delete(key)
HTTP Caching
from fastapi import FastAPI, Response
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
@app.get("/products/{product_id}")
async def get_product(product_id: int, response: Response):
product = await fetch_product(product_id)
response.headers["Cache-Control"] = "public, max-age=3600, stale-while-revalidate=86400"
response.headers["ETag"] = f'"{product["version"]}"'
return product
@app.get("/user/profile")
async def get_profile(response: Response):
response.headers["Cache-Control"] = "private, max-age=60"
return current_user.profile
@app.post("/products")
async def create_product(response: Response):
response.headers["Cache-Control"] = "no-store"
return await create_new_product()
Database Optimization
Query Optimization
users = User.query.all()
for user in users:
orders = Order.query.filter_by(user_id=user.id).all()
users = User.query.options(
joinedload(User.orders)
).all()
user_ids = [u.id for u in users]
orders = Order.query.filter(Order.user_id.in_(user_ids)).all()
orders_by_user = {}
for order in orders:
orders_by_user.setdefault(order.user_id, []).append(order)
users = db.execute("SELECT * FROM users WHERE status = 'active'")
users = db.execute("""
SELECT id, name, email
FROM users
WHERE status = 'active'
""")
def get_page(page, per_page):
offset = (page - 1) * per_page
return db.execute("""
SELECT * FROM products
ORDER BY created_at DESC
LIMIT :limit OFFSET :offset
""", {"limit": per_page, "offset": offset})
Connection Pooling
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool
engine = create_engine(
"postgresql://user:pass@localhost/db",
poolclass=QueuePool,
pool_size=10,
max_overflow=20,
pool_timeout=30,
pool_recycle=1800,
pool_pre_ping=True,
)
Frontend Performance
JavaScript Optimization
function updateItems(items) {
const container = document.getElementById('container');
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item.name;
container.appendChild(div);
});
}
function updateItemsFast(items) {
const container = document.getElementById('container');
const fragment = document.createDocumentFragment();
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item.name;
fragment.appendChild(div);
});
container.appendChild(fragment);
}
function resizeAll(elements) {
elements.forEach(el => {
const width = el.offsetWidth;
el.style.height = width + 'px';
});
}
function resizeAllFast(elements) {
const widths = elements.map(el => el.offsetWidth);
elements.forEach((el, i) => {
el.style.height = widths[i] + 'px';
});
}
function debounce(fn, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
const handleSearch = debounce((query) => {
performSearch(query);
}, 300);
function throttle(fn, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const handleScroll = throttle(() => {
updatePosition();
}, 16);
React Performance
function List({ items, onSelect }) {
return items.map(item => (
<Item
key={item.id}
onClick={() => onSelect(item.id)} // New function each render!
/>
));
}
function List({ items, onSelect }) {
const handleClick = useCallback((id) => {
onSelect(id);
}, [onSelect]);
return items.map(item => (
<Item
key={item.id}
id={item.id}
onClick={handleClick}
/>
));
}
function ExpensiveList({ items, filter }) {
const filtered = items.filter(i => i.name.includes(filter));
const sorted = filtered.sort((a, b) => a.name.localeCompare(b.name));
return sorted.map(item => <Item key={item.id} {...item} />);
}
function ExpensiveList({ items, filter }) {
const processed = useMemo(() => {
const filtered = items.filter(i => i.name.includes(filter));
return filtered.sort((a, b) => a.name.localeCompare(b.name));
}, [items, filter]);
return processed.map(item => <Item key={item.id} {...item} />);
}
const Item = React.memo(({ id, name, onClick }) => {
return <div onClick={() => onClick(id)}>{name}</div>;
});
import { FixedSizeList } from 'react-window';
function VirtualizedList({ items }) {
const Row = ({ index, style }) => (
<div style={style}>{items[index].name}</div>
);
return (
<FixedSizeList
height={400}
width={300}
itemCount={items.length}
itemSize={35}
>
{Row}
</FixedSizeList>
);
}
Async & Concurrency
Python Async
import asyncio
import aiohttp
async def fetch_sequential(urls):
results = []
async with aiohttp.ClientSession() as session:
for url in urls:
async with session.get(url) as response:
results.append(await response.json())
return results
async def fetch_concurrent(urls):
async with aiohttp.ClientSession() as session:
tasks = [fetch_one(session, url) for url in urls]
return await asyncio.gather(*tasks)
async def fetch_one(session, url):
async with session.get(url) as response:
return await response.json()
async def fetch_with_limit(urls, max_concurrent=10):
semaphore = asyncio.Semaphore(max_concurrent)
async def fetch_limited(session, url):
async with semaphore:
async with session.get(url) as response:
return await response.json()
async with aiohttp.ClientSession() as session:
tasks = [fetch_limited(session, url) for url in urls]
return await asyncio.gather(*tasks)
Thread/Process Pools
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import multiprocessing
def fetch_urls_threaded(urls):
def fetch_one(url):
response = requests.get(url)
return response.json()
with ThreadPoolExecutor(max_workers=10) as executor:
return list(executor.map(fetch_one, urls))
def process_items_parallel(items):
def process_one(item):
return heavy_computation(item)
with ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
return list(executor.map(process_one, items))
Performance Checklist
Backend
Frontend
Infrastructure
Output Format
When optimizing performance, provide:
## Performance Analysis
### Bottleneck Identified
**Type:** [Algorithm / I/O / Memory / Database]
**Location:** `file.py:42`
**Impact:** [High/Medium/Low]
### Current Performance
- Latency: X ms
- Memory: Y MB
- Complexity: O(...)
### Optimized Solution
**Before:**
```python
[Original slow code]
After:
[Optimized code]
Expected Improvement
- Latency: X ms → Y ms (Z% improvement)
- Memory: X MB → Y MB
- Complexity: O(...) → O(...)
Trade-offs
- [Trade-off 1]
- [Trade-off 2]
Additional Recommendations
- [Recommendation 1]
- [Recommendation 2]
## Notes
- Always measure before and after
- Profile in production-like conditions
- Consider the 80/20 rule - optimize what matters
- Don't sacrifice readability for micro-optimizations
- Cache invalidation is hard - plan carefully
- Premature optimization is the root of all evil