Performs comprehensive performance analysis covering database optimization, backend efficiency, frontend rendering, network optimization, and scalability.
Performs comprehensive performance analysis across database queries, backend algorithms, frontend rendering, and network requests. Use this when you need to identify bottlenecks, optimize slow code, or prepare for scale.
/plugin marketplace add dhofheinz/open-plugins/plugin install 10x-fullstack-engineer@open-pluginsreview/Performs comprehensive performance analysis covering database optimization, backend efficiency, frontend rendering, network optimization, and scalability.
Received from router: $ARGUMENTS (after removing 'performance' operation)
Expected format: scope:"review-scope" [depth:"quick|standard|deep"]
Extract from $ARGUMENTS:
Understand Performance Baseline:
# Check project structure and tech stack
ls -la
cat package.json 2>/dev/null || cat requirements.txt 2>/dev/null
# Identify performance-critical files
find . -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" | xargs grep -l "query\|fetch\|map\|filter\|useEffect\|useState" | head -20
# Check for existing performance monitoring
grep -r "performance\|timing\|profil\|benchmark" --include="*.ts" --include="*.js" | head -10
# Look for database queries
grep -r "SELECT\|INSERT\|UPDATE\|DELETE\|query\|execute" --include="*.ts" --include="*.js" --include="*.py" | head -15
# Check bundle configuration
ls -la | grep -E "webpack|vite|rollup|esbuild"
Query Optimization:
Connection Management:
Transaction Management:
Data Access Patterns:
Caching Strategy:
Code Examples - Database Performance:
// ❌ BAD: N+1 query problem
const users = await User.findAll();
for (const user of users) {
user.posts = await Post.findAll({ where: { userId: user.id } });
user.comments = await Comment.findAll({ where: { userId: user.id } });
}
// ✅ GOOD: Eager loading with includes
const users = await User.findAll({
include: [
{ model: Post },
{ model: Comment }
]
});
// ✅ BETTER: Only load what's needed
const users = await User.findAll({
attributes: ['id', 'name', 'email'], // Don't SELECT *
include: [
{
model: Post,
attributes: ['id', 'title', 'createdAt'],
limit: 5 // Only recent posts
}
]
});
// ❌ BAD: Loading all records without pagination
const allUsers = await User.findAll(); // Could be millions of records!
// ✅ GOOD: Pagination
const page = parseInt(req.query.page) || 1;
const limit = 20;
const offset = (page - 1) * limit;
const { rows: users, count } = await User.findAndCountAll({
limit,
offset,
order: [['createdAt', 'DESC']]
});
res.json({
users,
pagination: {
page,
limit,
total: count,
pages: Math.ceil(count / limit)
}
});
// ❌ BAD: Individual inserts
for (const item of items) {
await Item.create(item); // Each is a separate query!
}
// ✅ GOOD: Bulk insert
await Item.bulkCreate(items);
-- ❌ BAD: Missing index on frequently queried column
SELECT * FROM orders WHERE user_id = 123 AND status = 'pending';
-- This could be slow without an index!
-- ✅ GOOD: Add composite index
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
Algorithm Efficiency:
Async Operations:
Caching Strategy:
Resource Management:
Rate Limiting & Throttling:
Code Examples - Backend Performance:
// ❌ BAD: O(n²) complexity - nested loops
function findDuplicates(users) {
const duplicates = [];
for (let i = 0; i < users.length; i++) {
for (let j = i + 1; j < users.length; j++) {
if (users[i].email === users[j].email) {
duplicates.push(users[i]);
}
}
}
return duplicates;
}
// ✅ GOOD: O(n) complexity - using Map
function findDuplicates(users) {
const seen = new Map();
const duplicates = [];
for (const user of users) {
if (seen.has(user.email)) {
duplicates.push(user);
} else {
seen.set(user.email, user);
}
}
return duplicates;
}
// ❌ BAD: Sequential async operations
async function getUserData(userId) {
const user = await fetchUser(userId);
const posts = await fetchPosts(userId);
const comments = await fetchComments(userId);
return { user, posts, comments };
}
// ✅ GOOD: Parallel async operations
async function getUserData(userId) {
const [user, posts, comments] = await Promise.all([
fetchUser(userId),
fetchPosts(userId),
fetchComments(userId)
]);
return { user, posts, comments };
}
// ❌ BAD: Awaiting in loop
async function processUsers(userIds) {
const results = [];
for (const id of userIds) {
const result = await processUser(id); // Sequential!
results.push(result);
}
return results;
}
// ✅ GOOD: Parallel processing with Promise.all
async function processUsers(userIds) {
return Promise.all(userIds.map(id => processUser(id)));
}
// ✅ BETTER: Parallel with concurrency limit
async function processUsers(userIds) {
const concurrency = 5;
const results = [];
for (let i = 0; i < userIds.length; i += concurrency) {
const batch = userIds.slice(i, i + concurrency);
const batchResults = await Promise.all(batch.map(id => processUser(id)));
results.push(...batchResults);
}
return results;
}
// ❌ BAD: No caching for expensive operation
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2); // Recalculates same values!
}
// ✅ GOOD: Memoization
const fibCache = new Map();
function fibonacci(n) {
if (n <= 1) return n;
if (fibCache.has(n)) return fibCache.get(n);
const result = fibonacci(n - 1) + fibonacci(n - 2);
fibCache.set(n, result);
return result;
}
// ✅ BETTER: Iterative approach (faster)
function fibonacci(n) {
if (n <= 1) return n;
let prev = 0, curr = 1;
for (let i = 2; i <= n; i++) {
[prev, curr] = [curr, prev + curr];
}
return curr;
}
React Component Optimization:
List Rendering:
Image Optimization:
Bundle Optimization:
State Management:
Web Vitals Optimization:
Code Examples - Frontend Performance:
// ❌ BAD: Unnecessary re-renders
function UserList({ users, onDelete }) {
return users.map(user => (
<UserCard
key={user.id}
user={user}
onDelete={() => onDelete(user.id)} // New function every render!
/>
));
}
// ✅ GOOD: Memoized components
const UserCard = React.memo(({ user, onDelete }) => (
<div onClick={() => onDelete(user.id)}>
{user.name}
</div>
));
function UserList({ users, onDelete }) {
return users.map(user => (
<UserCard key={user.id} user={user} onDelete={onDelete} />
));
}
// ❌ BAD: Expensive calculation on every render
function ProductList({ products }) {
const sortedProducts = products
.sort((a, b) => b.rating - a.rating)
.slice(0, 10); // Recalculated every render!
return <div>{sortedProducts.map(p => <Product key={p.id} {...p} />)}</div>;
}
// ✅ GOOD: Memoized calculation
function ProductList({ products }) {
const sortedProducts = useMemo(() =>
products
.sort((a, b) => b.rating - a.rating)
.slice(0, 10),
[products] // Only recalculate when products change
);
return <div>{sortedProducts.map(p => <Product key={p.id} {...p} />)}</div>;
}
// ❌ BAD: No virtualization for large list
function MessageList({ messages }) {
return (
<div>
{messages.map(msg => (
<MessageItem key={msg.id} message={msg} />
))}
</div>
); // Renders ALL messages, even off-screen!
}
// ✅ GOOD: Virtualized list
import { FixedSizeList } from 'react-window';
function MessageList({ messages }) {
const Row = ({ index, style }) => (
<div style={style}>
<MessageItem message={messages[index]} />
</div>
);
return (
<FixedSizeList
height={600}
itemCount={messages.length}
itemSize={80}
width="100%"
>
{Row}
</FixedSizeList>
); // Only renders visible items!
}
// ❌ BAD: Entire library imported
import moment from 'moment'; // Imports entire 70KB library!
// ✅ GOOD: Lightweight alternative
import { format } from 'date-fns'; // Tree-shakeable, smaller
// ❌ BAD: Lodash imported entirely
import _ from 'lodash';
// ✅ GOOD: Specific imports
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
API Optimization:
Caching & CDN:
Compression:
Resource Loading:
Code Examples - Network Performance:
// ❌ BAD: No debouncing for search
function SearchBox() {
const [query, setQuery] = useState('');
const handleChange = async (e) => {
setQuery(e.target.value);
await fetchResults(e.target.value); // API call on every keystroke!
};
return <input value={query} onChange={handleChange} />;
}
// ✅ GOOD: Debounced search
import { debounce } from 'lodash';
function SearchBox() {
const [query, setQuery] = useState('');
const fetchResultsDebounced = useMemo(
() => debounce((q) => fetchResults(q), 300),
[]
);
const handleChange = (e) => {
setQuery(e.target.value);
fetchResultsDebounced(e.target.value);
};
return <input value={query} onChange={handleChange} />;
}
// ❌ BAD: Multiple API calls
const user = await fetch('/api/user/123').then(r => r.json());
const posts = await fetch('/api/user/123/posts').then(r => r.json());
const followers = await fetch('/api/user/123/followers').then(r => r.json());
// ✅ GOOD: Single API call with all data
const userData = await fetch('/api/user/123?include=posts,followers')
.then(r => r.json());
// ✅ BETTER: GraphQL for flexible data fetching
const userData = await graphqlClient.query({
query: gql`
query GetUser($id: ID!) {
user(id: $id) {
name
email
posts(limit: 10) { title }
followers(limit: 5) { name }
}
}
`,
variables: { id: '123' }
});
Monitoring Tools:
# Check bundle size
npm run build
ls -lh dist/ # Check output sizes
# Analyze bundle composition
npm install --save-dev webpack-bundle-analyzer
# Add to webpack config and analyze
# Run Lighthouse audit
npx lighthouse https://your-site.com --view
# Check Core Web Vitals
# Use Chrome DevTools -> Performance
# Use Lighthouse or WebPageTest
Performance Metrics:
Profiling:
Horizontal Scalability:
Vertical Scalability:
Database Scalability:
Caching for Scale:
Quick Depth (10-15 min):
Standard Depth (30-40 min):
Deep Depth (60-90+ min):
# Performance Review: [Scope]
## Executive Summary
**Reviewed**: [What was reviewed]
**Depth**: [Quick|Standard|Deep]
**Performance Rating**: [Excellent|Good|Needs Optimization|Critical Issues]
### Overall Performance Assessment
**[Optimized|Acceptable|Needs Improvement|Poor]**
[Brief explanation]
### Key Performance Metrics
- **Average Response Time**: [Xms]
- **Database Query Time**: [Xms]
- **Bundle Size**: [XKB]
- **Largest Contentful Paint**: [Xs]
- **Time to Interactive**: [Xs]
### Priority Actions
1. [Critical performance fix 1]
2. [Critical performance fix 2]
---
## Critical Performance Issues 🚨
### [Issue 1 Title]
**File**: `path/to/file.ts:42`
**Category**: Database|Backend|Frontend|Network
**Impact**: [Severe slowdown, timeout, memory leak, etc.]
**Current Performance**: [Xms, XKB, etc.]
**Expected Performance**: [Target]
**Root Cause**: [Why this is slow]
**Optimization**: [Specific fix]
```typescript
// Current code (slow)
[slow code]
// Optimized implementation
[fast code]
// Performance improvement: [X% faster, XKB smaller, etc.]
[Repeat for each critical issue]
[Similar format for high impact issues]
[Similar format for medium impact issues]
[Similar format for low impact issues]
Query Performance:
Optimization Recommendations:
Algorithm Complexity:
Async Performance:
Optimization Recommendations:
Bundle Analysis:
Rendering Performance:
Web Vitals:
| Metric | Current | Target | Status |
|---|---|---|---|
| LCP | [Xs] | < 2.5s | ✅ / ⚠️ / ❌ |
| FID | [Xms] | < 100ms | ✅ / ⚠️ / ❌ |
| CLS | [X] | < 0.1 | ✅ / ⚠️ / ❌ |
| TTI | [Xs] | < 3.8s | ✅ / ⚠️ / ❌ |
Optimization Recommendations:
API Performance:
Resource Loading:
Optimization Recommendations:
Current Load Capacity: [X requests/second] Bottlenecks for Scaling:
Horizontal Scaling: [Ready|Needs Work|Not Possible] Vertical Scaling: [Efficient|Acceptable|Memory/CPU intensive]
Recommendations for Scale:
Expected Overall Improvement: [X% faster, XKB smaller, etc.]
Profiling Tools:
Monitoring Tools:
## Agent Invocation
This operation MUST leverage the **10x-fullstack-engineer** agent with performance expertise.
## Best Practices
1. **Measure First**: Use profiling data, not assumptions
2. **Optimize Hotspots**: Focus on code that runs frequently
3. **Balance Trade-offs**: Consider readability vs performance
4. **Think Scale**: How will this perform with 10x, 100x data?
5. **User-Centric**: Optimize for perceived performance
6. **Incremental Optimization**: Make measurable improvements iteratively