12 Prompts for Code Performance Optimization: Finding and Fixing Bottlenecks
Performance optimization is a critical skill for any software engineer. According to the 2025 Stack Overflow Developer Survey, 68% of professional developers report spending at least 10% of their time profiling and optimizing code. Yet many teams struggle to systematically identify bottlenecks and apply effective fixes. This guide provides 12 copy-paste ready prompts you can use with AI coding assistants (like ChatGPT, Claude, or GitHub Copilot) to accelerate your optimization workflow. Each prompt addresses a specific task—from initial profiling to memory analysis and algorithmic refactoring.
How to Use These Prompts
Each prompt is designed for a specific scenario. Replace the placeholders (e.g., [your code snippet]) with your actual code. The prompts assume you have a basic understanding of performance concepts like time complexity, memory allocation, and profiling tools. For best results, run the prompts iteratively: start with identification, then move to analysis, and finally to implementation.
1. Identify Hotspots with Profiling Data
Task: Given raw profiling output (e.g., from cProfile, perf, or Xcode Instruments), identify the top 3 functions consuming the most CPU time.
Prompt:
I have profiling output from [profiling tool name]. Here is the raw data:
[raw profiling output or screenshot description]
Identify the top 3 functions by cumulative execution time. For each, explain:
- Why it might be slow (algorithmic complexity, I/O, etc.)
- One concrete optimization strategy (e.g., caching, batching, vectorization)
- The expected impact (e.g., 30% reduction in wall-clock time)
Usage example: A developer runs python -m cProfile myscript.py and pastes the sorted output. The AI highlights that process_data is called 500,000 times with O(n²) complexity, suggesting a loop invariant hoisting fix.
2. Analyze Time Complexity of a Code Block
Task: Determine the worst-case time complexity of a given function and suggest improvements.
Prompt:
Analyze the time complexity of this function:
[your code snippet]
Provide:
1. Big O notation for worst, average, and best cases
2. The specific line(s) causing the bottleneck
3. A refactored version with lower complexity (e.g., O(n²) → O(n log n))
4. Brief justification of why the new version is faster
Usage example: For a nested loop searching for duplicates (O(n²)), the AI suggests using a hash set to reduce to O(n), with example code.
3. Detect Memory Leaks in Long-Running Processes
Task: Identify potential memory leaks in a server or daemon application.
Prompt:
Examine this code for memory leaks. The application runs for days and gradually consumes more memory:
[code snippet]
Check for:
- Unclosed file handles or network connections
- Growing global dictionaries or lists
- Circular references (especially in Python with gc)
- Caching without eviction policy
Suggest fixes for each issue found.
Usage example: A Node.js server that accumulates request metadata in a global Map without cleanup—the AI recommends using Map with TTL or a bounded LRU cache.
4. Optimize Database Query Performance
Task: Improve slow database queries identified in logs or via EXPLAIN ANALYZE.
Prompt:
Here is a slow SQL query and its EXPLAIN ANALYZE output:
[SQL query]
[EXPLAIN output]
Analyze:
1. Which index (if any) is being used?
2. Which step has the highest cost (e.g., sequential scan, nested loop)?
3. Suggest schema changes (new indexes, composite keys, partitioning) or query rewrites (join order, subquery elimination).
4. Provide the optimized query and expected improvement.
Usage example: A query with a sequential scan on a 10M-row table—the AI proposes a composite index on (user_id, created_at) and rewrites the WHERE clause to use index-only scan.
5. Reduce Redundant Computations with Caching
Task: Identify repeated calculations and suggest caching strategies.
Prompt:
In this code, the same expensive computation is performed multiple times:
[code snippet]
Implement a caching layer using [language-specific cache, e.g., functools.lru_cache in Python, memoization in JS]. Show:
- Where to add the cache
- Cache key design
- Eviction policy (e.g., LRU, TTL)
- Estimated reduction in calls (based on call frequency analysis)
Usage example: A recursive Fibonacci function is called with identical arguments many times—the AI adds @lru_cache(maxsize=128) and shows a 90% reduction in calls.
6. Benchmark Two Alternative Implementations
Task: Compare the performance of two code variants using microbenchmarking.
Prompt:
I have two implementations of the same functionality:
Version A:
[code A]
Version B:
[code B]
Write a benchmark script that:
- Runs each version 1000 times
- Measures median and p99 latency
- Accounts for JIT warm-up (discard first 100 runs)
- Outputs a clear comparison table
- Identifies which variant is faster and by what margin
Usage example: Comparing list comprehension vs. map() in Python—the benchmark shows list comprehension is 15% faster for typical data sizes.
7. Parallelize Sequential Code
Task: Convert a sequential loop into parallel execution using threads or processes.
Prompt:
This function processes items sequentially. I want to parallelize it:
[code snippet]
Analyze:
1. Is the workload CPU-bound or I/O-bound?
2. Recommend threading (for I/O) vs multiprocessing (for CPU) vs async
3. Provide a refactored version using [language-specific library, e.g., concurrent.futures in Python, async/await in JS]
4. Warn about potential issues (race conditions, GIL, resource limits)
Usage example: A script downloading 100 files sequentially (I/O-bound) – the AI rewrites it with ThreadPoolExecutor and shows a 4x speedup on a typical machine.
8. Spot Inefficient Data Structures
Task: Replace suboptimal data structures (e.g., list for membership tests, dict for ordered iteration).
Prompt:
In this code, I use [data structure A] for [purpose]. Evaluate if [data structure B] would be more efficient:
[code snippet]
Compare:
- Time complexity for common operations (insert, lookup, delete, iteration)
- Memory overhead
- Code readability impact
If replacement is beneficial, provide the refactored code.
Usage example: Using a list for membership checks in a 100K-element collection—the AI suggests converting to a set, reducing O(n) lookups to O(1).
9. Minimize I/O Blocking in File Processing
Task: Optimize code that reads/writes large files sequentially.
Prompt:
This code processes a large file line by line, but it's slow:
[code snippet]
Suggest improvements:
- Use buffered I/O (e.g., BufferedReader in Java, open() with buffer size in Python)
- Use memory-mapped files if applicable
- Batch writes instead of per-line writes
- Use asynchronous I/O for non-blocking reads
Provide a refactored version with benchmark comparison.
Usage example: A Python script writing 1M lines with file.write() each time – the AI changes to writelines() with a buffer, reducing runtime from 30s to 2s.
10. Detect and Fix Unnecessary Object Allocations
Task: Reduce GC pressure by identifying temporary objects created inside hot loops.
Prompt:
Examine this hot loop for unnecessary object allocations:
[code snippet]
Look for:
- Creating new objects inside the loop (e.g., `new String()` in Java, `[]` inside for-loop in Python)
- Autoboxing in Java
- String concatenation in a loop (use StringBuilder)
- Temporary tuples/list comprehensions that can be replaced with generator expressions
Provide a refactored version with allocation counts reduced.
Usage example: A Java loop concatenating strings with + – the AI replaces it with StringBuilder.append() and shows a 50% reduction in GC pauses.
11. Profile with Flame Graphs
Task: Generate and interpret a flame graph from profiling data.
Prompt:
I have profiling data from [tool, e.g., perf, DTrace, py-spy]. Generate a flame graph visualization command and help me interpret it:
[raw profiling data or instructions]
Explain:
- Which function appears as the widest stack frame?
- Are there any "plateaus" indicating contention?
- What should I prioritize: optimizing the widest frame or addressing a deep call chain?
- Next steps based on the graph.
Usage example: A developer runs perf script on a Node.js app, the AI generates a FlameGraph command and identifies that JSON.parse is the top consumer, suggesting a streaming parser.
12. Automate Performance Regression Detection
Task: Set up a continuous benchmark to catch speed regressions before deployment.
Prompt:
I want to add a performance regression test to my CI pipeline. Here is my current test suite:
[test file or description]
Design a simple benchmark that:
- Measures execution time of critical paths (e.g., API endpoint, data processing)
- Compares against a baseline (previous commit or fixed threshold)
- Fails if the new version is >10% slower
- Uses [language-specific library, e.g., pytest-benchmark, benchmark.js]
- Outputs results in a machine-readable format (JSON)
Provide the complete benchmark code and CI config snippet (e.g., GitHub Actions step).
Usage example: A team adds pytest-benchmark to their Python project, with a GitHub Action that runs benchmarks on every PR and comments with the results.
Summary Table
| Prompt # | Task | Typical Use Case | Expected Improvement |
|---|---|---|---|
| 1 | Identify hotspots | Post-profiling analysis | Up to 80% time reduction |
| 2 | Time complexity analysis | Algorithmic optimization | O(n²) → O(n log n) |
| 3 | Memory leak detection | Long-running services | Prevent OOM crashes |
| 4 | Database query optimization | Slow SQL queries | 10x query speedup |
| 5 | Caching redundant computations | Repeated calculations | 90% fewer calls |
| 6 | Benchmarking alternatives | Choosing between implementations | 15-30% speedup |
| 7 | Parallelization | Batch processing | 4x speedup (I/O) |
| 8 | Data structure replacement | Membership tests, ordering | O(n) → O(1) |
| 9 | I/O optimization | File processing | 15x speedup |
| 10 | Allocation reduction | Hot loops, GC pressure | 50% fewer GC pauses |
| 11 | Flame graph profiling | Deep performance analysis | Visual bottleneck identification |
| 12 | Regression detection | CI/CD pipeline | Catch regressions early |
Conclusion
Performance optimization doesn't have to be guesswork. By using these structured prompts, you can systematically profile, analyze, and improve your code. Start with prompt #1 to identify your biggest bottleneck, then apply the relevant optimization prompt. The key is to measure before and after—always verify your changes with benchmarks.
Try one prompt today: paste your profiling output into your favorite AI tool and see what it finds. For deeper learning, refer to the official documentation of profiling tools like cProfile or perf. Happy optimizing!
Comments