Introduction
Performance optimization is a critical skill for any developer—it directly impacts user experience, infrastructure costs, and scalability. However, identifying the exact slow spots and deciding what to fix can be time-consuming. Large language models (LLMs) have emerged as powerful allies in this process, capable of analyzing code, suggesting improvements, and even generating optimized versions. Below you’ll find 12 ready-to-use prompts designed to help you profile, diagnose, and optimize code across languages and frameworks. Each prompt is paired with a concrete example and an explanation of why it works. Use them with ChatGPT, Claude, or any code-savvy assistant.
1. Prompts for Profiling and Identifying Bottlenecks
1. Analyze Hotspots and Suggest Profiling Tools
Prompt:
Analyze the following code snippet and identify the most time-consuming operations. Then suggest the best profiling tool for [language] and explain how to use it to confirm your findings.
[Paste code]
Why it works: It forces the AI to reason about computational complexity and real-world runtime, while also pointing you to practical tools (e.g., cProfile for Python, perf for C++, Chrome DevTools for JavaScript).
Example usage: You paste a Python function that processes large CSV files. The AI might respond: “The nested loop reading line by line is O(n²). Use cProfile with python -m cProfile script.py to confirm that parse_line takes 70% of the time. Consider using pandas.read_csv with chunking.”
2. Optimize Nested Loops with Algorithmic Alternatives
Prompt:
Given this function that uses nested loops (O(n²)), propose alternative algorithms or data structures to reduce time complexity. Provide a before-and-after code comparison and explain the trade-offs.
[Paste code]
Why it works: Nested loops are a classic bottleneck. The AI will suggest hash maps, sorting, two-pointer techniques, etc., and highlight memory vs. speed trade-offs.
Example output: For a brute-force find_duplicates the AI might offer a set()-based solution, reducing complexity from O(n²) to O(n), with a memory trade-off of O(n).
3. Memory Leak Detection
Prompt:
Detect potential memory leaks in this code snippet. For each suspect, explain the root cause and propose a fix. If the language has built-in memory profiling tools, mention them.
[Paste code]
Why it works: Memory leaks are subtle. The AI can spot unclosed file handles, forgotten event listeners, circular references, or cached objects that never expire. It will also name tools like valgrind or heapy.
4. Database Query Performance Review
Prompt:
Evaluate the performance of this SQL query. Suggest indexing and query restructuring to reduce execution time. Show an `EXPLAIN ANALYZE` output example that confirms the improvement.
[SQL query]
Why it works: Database queries are a common source of slowness. The AI will recommend composite indexes, covering indexes, avoiding SELECT *, and restructuring joins.
2. Prompts for Optimizing Data Structures and Algorithms
5. Data Structure Selection
Prompt:
Given this use case: [description of operations – e.g., frequent inserts and lookups by ID], recommend the optimal data structure. Compare time and space complexity for all common alternatives (list, set, dict, tree, hash table).
[Paste brief usage context]
Why it works: It forces a systematic comparison, helping you choose the right tool for the job.
6. Recursion to Iteration Refactoring
Prompt:
Refactor this recursive function into an iterative version to avoid stack overflow and improve performance on large inputs. Explain why the iterative version is faster.
[Paste recursive code]
Why it works: Recursion overhead (function call stack) can be eliminated. The AI will produce an explicit stack or loop-based approach.
7. Caching and Lazy Evaluation
Prompt:
Suggest caching or lazy evaluation strategies for this computation-heavy function. Consider memoization, LRU cache, or deferred execution. Provide code examples for each.
[Paste function]
Why it works: Redundant computation is a performance killer. The AI will show you patterns like functools.lru_cache, WeakMap, or generator-based pipelines.
3. Language-Specific Optimizations
8. Python: Global Interpreter Lock (GIL) Mitigation
Prompt:
Analyze this Python code for GIL contention. Suggest using multiprocessing, asyncio, or threading (with a GIL-friendly library like NumPy) to improve parallelism. Show a speed comparison.
[Paste CPU-bound or I/O-bound code]
Why it works: The AI will distinguish CPU vs. I/O bound scenarios and propose ProcessPoolExecutor for CPU and asyncio for I/O.
9. JavaScript: Async Performance
Prompt:
Identify blocking operations in this JavaScript code. Rewrite it to use async/await, `Promise.all`, or Web Workers to keep the main thread free. Also suggest tools like Lighthouse to verify.
[Paste code]
Why it works: Blocking the event loop destroys user experience. The AI will restructure to non-blocking patterns.
10. SQL: Using EXPLAIN ANALYZE
Prompt:
Rewrite this SQL query and add an `EXPLAIN ANALYZE` plan. Then explain which parts are slow (e.g., full table scans, sequential reads, nested loop joins) and suggest index or schema changes.
[SQL query]
Why it works: Forces the AI to simulate query execution analysis, teaching you how to read EXPLAIN output.
4. Code Review and Best Practices
11. Senior Developer Review for Anti-patterns
Prompt:
Act as a senior developer with 15 years of experience. Review this code for performance anti-patterns (e.g., premature optimization, unnecessary allocations, hidden O(n²) operations). Provide a refactored version with inline comments justifying each change.
[Paste code]
Why it works: The AI takes on an expert persona and gives holistic feedback, not just micro-optimizations.
12. Performance Best Practices Checklist
Prompt:
Generate a concise checklist of performance best practices for [language/framework] that covers: memory management, algorithm choice, I/O handling, and concurrency. For each point, include a code snippet of a bad and a good example.
Why it works: This delivers a reusable reference you can integrate into your team’s code reviews.
Conclusion
Using AI assistants for performance optimization doesn’t replace your own profiling and benchmarking—it accelerates the discovery phase and offers fresh perspectives. Combine these prompts with real profiler output (like flame graphs or tracing) to validate suggestions. Start with the prompts that target your current pain point, adapt them to your language, and iterate. The best optimized code is not just faster; it’s also cleaner and more maintainable. Try one of these prompts today on a piece of code you know is slow, and measure the difference.
Comments