12 Prompts for Code Performance Optimization: Find Bottlenecks and Speed Up Your Application
Performance optimization is rarely about rewriting everything from scratch. Often, the biggest gains come from identifying a single bottleneck and applying a targeted fix. But finding that bottleneck can be tricky, especially in large codebases. That’s where well-crafted prompts for AI assistants (like ChatGPT or GitHub Copilot) can save hours. Below are 12 battle‑tested prompts I use in daily development work. Each prompt includes a real‑world scenario, the exact wording, and a concrete result.
1. Profile a function with cProfile (Python)
Prompt: "Given this Python function, write a script that uses cProfile to profile it and then pstats to print the top 10 cumulative time calls. Show the output and point out the slowest part."
Example: You have a heavy data transformation function. After running the prompt, you see that nested_loop takes 78% of the time. You then refactor it with a dictionary lookup and cut runtime from 4.3s to 0.2s.
Result: Immediate identification of the bottleneck without manual instrumentation.
2. Explain a flame graph from a Node.js profile
Prompt: "Here is a flame graph from Node.js profiling (picture attached). Explain which functions are hot, which are waiting on I/O, and suggest where to start optimization."
Example: The flame graph showed a large JSON.parse block inside a loop. By batching the JSON operations, response time dropped from 1200ms to 300ms.
Result: AI interprets visual profiling data and maps it to concrete code changes.
3. Rewrite a slow PostgreSQL query with execution plan
Prompt: "Here is a PostgreSQL query that takes 12 seconds. Here is its EXPLAIN ANALYZE output. Rewrite it to use an index or change the join strategy. Explain why the new version is faster."
Example: The original query had a sequential scan on a 5M row table. The suggested rewrite added a composite index and changed IN to EXISTS. Execution time went to 80ms.
Result: AI leverages database internals to produce an optimized query plan.
4. Suggest async patterns for I/O-bound Python code
Prompt: "This Python function reads 100 files sequentially and processes them. Convert it to asyncio with aiofiles. Show the before/after benchmark."
Example: Sequential reading took 45 seconds; async version completed in 7 seconds. The prompt also handled error propagation and limited concurrency with asyncio.Semaphore.
Result: AI writes production‑ready async code, not just a toy example.
5. Reduce memory usage in a React component
Prompt: "This React component re‑renders too often and causes jank. Identify the unnecessary re‑renders using React.memo, useMemo, and useCallback where appropriate. Provide the optimized version and a note on when to avoid these optimizations."
Example: A large list component re‑rendered every keystroke. After applying React.memo and memoizing the filtering function, paint time dropped from 16ms per frame to 4ms.
Result: AI explains trade‑offs (e.g., memoization overhead vs. benefit) and delivers a diff.
6. Find N+1 queries in a Rails API
Prompt: "I have a Ruby on Rails endpoint that returns a list of posts with their authors. It currently makes N+1 database calls. Use includes or preload to fix it. Show the ActiveRecord log before and after."
Example: The endpoint made 101 queries for 100 posts. After adding includes(:author), it made only 2 queries. Response time fell from 3.5s to 0.4s.
Result: AI pinpoints the exact missing eager load and validates with log output.
7. Optimize a Docker image size
Prompt: "Here is my Dockerfile for a Python app. The image is 1.2GB. Use multi‑stage builds, slim base images, and layer caching to reduce it. Explain each change."
Example: Final image size dropped to 180MB. The prompt removed build dependencies, switched to python:3.11-slim, and used .dockerignore.
Result: AI provides a clear diff and rationale for every layer reduction.
8. Analyze a slow CSS animation
Prompt: "This CSS animation stutters on mobile. Check if any properties trigger layout or paint. Replace them with transform and opacity only. Also suggest using will-change correctly."
Example: The animation used left and margin, causing layout thrashing. After switching to transform: translateX(...), frame rate went from 20fps to 60fps.
Result: AI identifies compositor‑only properties and warns about will-change overuse.
9. Parallelize a CPU‑bound task in Go
Prompt: "This Go function processes a million numbers sequentially. Rewrite it to use goroutines and a worker pool. Include a benchmark to compare sequential vs parallel execution on my 8‑core machine."
Example: Sequential took 4.2 seconds; parallel with 8 workers took 0.9 seconds. The prompt also handled proper synchronization with sync.WaitGroup.
Result: AI generates idiomatic Go concurrency code with correct resource management.
10. Diagnose a memory leak in a Java application
Prompt: "I have a Java heap dump (Hprof file). Write a script using Eclipse Memory Analyzer (MAT) OQL to find the biggest objects and suggest a code fix. Or if you can't run MAT, interpret this summary: 'byte[] instances: 500,000, each ~10KB, held by HashMap in CacheService'."
Example: The leak came from an unbounded cache map. The prompt suggested adding a size limit with LinkedHashMap or Guava's CacheBuilder. Memory usage stabilized at 200MB.
Result: Even without the actual dump, AI guides the debugging process using memory statistics.
11. Replace a for‑loop with vectorized NumPy operations
Prompt: "This Python loop over a large array takes 30 seconds. Convert it to vectorized NumPy operations. Show the speed comparison with timeit."
Example: Original loop: for i in range(len(arr)): out[i] = arr[i] * 2 + 1. Vectorized: out = arr * 2 + 1. Loop took 30s, vectorized took 0.03s.
Result: AI leverages library‑specific optimizations (SIMD, C‑level loops).
12. Optimize a slow static site build (Next.js)
Prompt: "My Next.js static export takes 5 minutes because of a heavy data fetching step. Use getStaticPaths with fallback: false, but also profile the fetching function. Suggest caching the data or using incremental static regeneration."
Example: The site fetched 5000 pages from a slow API each build. The prompt recommended fetching once and writing to a JSON file, then reading from disk in getStaticProps. Build time dropped to 40 seconds.
Result: AI combines build‑time caching with framework‑specific best practices.
Conclusion
These 12 prompts are not magic – they are structured conversations that force an AI to focus on concrete observations (profiler output, logs, execution plans) and produce actionable code. Next time you hit a performance wall, try one of these prompts instead of guessing. The right question cuts debugging time in half.
What’s your go‑to performance prompt? Share it in the comments or on our community forum – I’m always looking for new ideas to add to this collection.
Comments