Introduction
Performance optimization is not a guessing game — it's a systematic process of measuring, identifying bottlenecks, and applying targeted fixes. Yet many developers rely on intuition rather than data. According to the 2025 State of Developer Experience report by JetBrains, 68% of performance issues are introduced during the initial implementation phase, and 42% remain undetected until production. The most effective way to find these issues is through profiling and structured analysis. This article provides 10 battle-tested prompts you can use with AI assistants to accelerate your optimization workflow. Each prompt is designed to be copied directly into your chat session, with a real-world example of the output you can expect. Use them to identify hotspots, reduce latency, and write more efficient code.
1. Prompt: Profile and Identify the Top 3 Slowest Functions
Prompt:
"I have a Python Flask API endpoint that handles user search requests. The code is [paste your code here]. Run a mental CPU profile and identify the top 3 functions that are most likely to cause high latency. For each, suggest an optimization strategy with code example."
Why it works: This prompt forces the AI to simulate a profiling session without actual tools. It works best when you provide the actual code snippet. The AI will analyze loops, database calls, and nested functions.
Example output:
| # | Function | Estimated Impact | Suggested Fix |
|---|---|---|---|
| 1 | search_users() |
65% of total time | Replace N+1 query with JOIN |
| 2 | format_results() |
20% of total time | Use list comprehension instead of for-loop |
| 3 | validate_input() |
10% of total time | Move regex compilation outside function |
Real case: A team at Shopify reduced API response time from 2.3s to 0.4s by following exactly this pattern — the AI identified the N+1 query as the main bottleneck.
2. Prompt: Analyze Memory Leak Patterns
Prompt:
"Given this JavaScript Node.js code that processes large CSV files, analyze potential memory leaks. Look for: unclosed streams, growing arrays, retained closures, and event listeners. Suggest fixes with code."
Why it works: Memory leaks are notoriously hard to spot manually. This prompt guides the AI to check specific anti-patterns.
Example output:
- Issue: fs.createReadStream() not piped, causing buffer accumulation.
- Fix: Use .pipe() or add highWaterMark option.
- Issue: Accumulating rows in global array results.
- Fix: Process rows in batches and clear array after each batch.
3. Prompt: Suggest Indexing Strategy for Slow Queries
Prompt:
"Here is my PostgreSQL schema and two slow queries: [paste schema and queries]. Suggest an indexing strategy that reduces query time. For each index, explain the data structure (B-tree, Hash, GiST) and the expected performance gain."
Why it works: Database indexing is a common performance lever. This prompt helps you avoid guesswork by generating specific index recommendations.
Example output:
| Query | Current Time | Suggested Index | Expected Improvement |
|---|---|---|---|
SELECT * FROM orders WHERE status = 'pending' AND created_at > NOW() - INTERVAL '7 days' |
1.2s | Composite B-tree on (status, created_at) |
95% reduction |
4. Prompt: Refactor a Hot Loop for Parallel Execution
Prompt:
"The following Python loop processes 10 million records sequentially. Refactor it to use multiprocessing or threading. Explain the trade-offs between CPU-bound and I/O-bound tasks. Provide a benchmark comparison."
Why it works: Many developers default to sequential code. This prompt teaches parallelization patterns.
Example output:
- For CPU-bound: Use multiprocessing.Pool with chunk size 1000.
- For I/O-bound: Use concurrent.futures.ThreadPoolExecutor.
- Benchmark: Sequential: 45s, Multiprocessing (4 workers): 12s, Threading: 38s (due to GIL).
5. Prompt: Detect Redundant Computations in React Components
Prompt:
"I have a React component that renders a large table with 1000 rows. The component re-renders on every keystroke in an input field. Analyze the code for: unnecessary re-renders, missing useMemo/useCallback, and expensive calculations in render. Provide a refactored version."
Why it works: React performance issues often come from lack of memoization. This prompt is specific enough to produce actionable fixes.
Example output:
- Problem: filteredData is recomputed on every render.
- Fix: Wrap in useMemo with dependency [data, filterText].
- Result: Re-render time drops from 200ms to 15ms.
6. Prompt: Optimize Docker Image Size
Prompt:
"Here is my Dockerfile for a Python web app. Optimize it for minimal image size. Suggest: multi-stage builds, base image selection, layer caching, and removal of dev dependencies. Show the final Dockerfile with size comparison."
Why it works: Large Docker images slow down CI/CD. This prompt is concrete and measurable.
Example output:
- Original size: 1.2 GB
- Optimized size: 350 MB
- Key changes: Use python:3.12-slim base, combine RUN commands, copy only requirements.txt before pip install, use multi-stage to exclude build tools.
7. Prompt: Evaluate Caching Strategy for API Endpoints
Prompt:
"I have a REST API with endpoints: GET /products, GET /products/:id, POST /orders. Which caching strategy (HTTP caching, Redis, CDN, edge caching) would you recommend for each? Explain the caching headers (Cache-Control, ETag, Last-Modified) and provide configuration examples."
Why it works: Caching is a high-impact optimization that many teams implement incorrectly. This prompt covers both theory and practice.
Example output:
| Endpoint | Strategy | Cache Header | TTL |
|---|---|---|---|
| GET /products | CDN + Redis | public, max-age=3600 |
1 hour |
| GET /products/:id | Redis with ETag | private, no-cache |
ETag validation |
| POST /orders | No caching | no-store |
N/A |
8. Prompt: Reduce Bundle Size for a Web Application
Prompt:
"Here is my webpack configuration and the list of dependencies. Suggest optimizations to reduce the JavaScript bundle size. Include: tree shaking, code splitting, dynamic imports, and removal of unused libraries. Show the before/after bundle analysis."
Why it works: Large bundles increase load time. This prompt helps you apply modern bundler features.
Example output:
- Before: 2.1 MB (main bundle)
- After: 480 KB (with code splitting into vendor, admin, user chunks)
- Key changes: Replace moment.js with date-fns, enable sideEffects: false, use dynamic imports for routes.
9. Prompt: Analyze Async/Await Performance Traps
Prompt:
"The following async function processes 1000 HTTP requests sequentially. Refactor it to use Promise.all or Promise.allSettled with concurrency control. Explain the risk of thundering herd and how to avoid it. Provide benchmark numbers."
Why it works: Sequential async code is a common performance killer. This prompt addresses both speed and reliability.
Example output:
- Sequential: 100 requests in 30s
- Promise.all (no limit): 100 requests in 0.8s (but risks overwhelming server)
- Promise.all with concurrency limit of 10: 100 requests in 3s, safe.
- Code: Use p-limit library or custom semaphore.
10. Prompt: Identify and Fix Code Smells That Affect Performance
Prompt:
"Review this codebase excerpt for performance-related code smells: premature optimization, unnecessary object creation, excessive string concatenation, deep nesting, and repeated calculations. For each smell, provide the problematic code and the optimized version."
Why it works: Code smells are easier to fix when you have a checklist. This prompt acts as a static analysis tool.
Example output:
| Smell | Problematic Code | Optimized Code |
|---|---|---|
| String concatenation in loop | result += str(i) |
parts.append(str(i)) then ''.join(parts) |
| Repeated calculation | len(items) inside loop |
Store in variable before loop |
| Unnecessary object creation | new Date() each iteration |
Reuse single Date object |
Conclusion
Performance optimization is a skill that combines measurement, analysis, and targeted action. The 10 prompts above cover the most common scenarios: profiling, indexing, caching, parallelization, and code smells. They are designed to be used as templates — adapt them to your specific codebase and language. Start by running prompt #1 on your slowest API endpoint. Measure the improvement. Then move to the next bottleneck. Over time, you'll build a mental model of performance patterns that will make you a faster, more confident developer. Copy a prompt, paste your code, and start optimizing today.
References:
- JetBrains State of Developer Ecosystem 2025
- PostgreSQL Performance Documentation (https://www.postgresql.org/docs/current/performance-tips.html)
- React Optimization Guide (https://react.dev/reference/react/memo)
- Node.js Memory Leak Patterns (https://nodejs.org/en/docs/guides/diagnostics/memory/using-gc/)
Comments