15 Prompts for Code Performance Optimization: A Developer's Cheat Sheet

15 Prompts for Code Performance Optimization: A Developer's Cheat Sheet

Performance optimization is a critical skill for any developer. Whether you're working on a high-traffic web application, a data pipeline, or a mobile app, finding and eliminating bottlenecks can dramatically improve user experience and reduce infrastructure costs. Instead of manually scanning thousands of lines of code, you can use carefully crafted prompts to guide AI assistants in profiling, analyzing, and refactoring your codebase. This collection provides fifteen ready-to-use prompts, each targeting a specific optimization scenario. Each prompt is designed to be copy-pasted into an AI tool like ChatGPT, Claude, or Copilot, and includes real-world examples, code snippets, and expected outcomes.


1. Profile CPU-Bound Code

Task: Identify which functions consume the most CPU time.

Prompt:

You are a performance engineer. Analyze the following Python code and identify the top 3 CPU-intensive functions. For each, suggest a specific optimization (e.g., algorithm change, memoization, vectorization). Provide before/after code snippets.

[Paste your code here]

Example:
Input: A recursive Fibonacci function (fib(40)).
Output: The AI identifies fib() as the bottleneck, suggests memoization, and shows a 99% speedup (from 30 seconds to 0.01 seconds).


2. Detect Memory Leaks

Task: Find objects that are not being garbage collected.

Prompt:

Given the following JavaScript code (Node.js environment), list all potential memory leaks. For each leak, explain the root cause (e.g., closures, global variables, event listeners) and provide a fix. Include a command to check heap snapshots using Chrome DevTools.

[Paste your code here]

Example:
Input: A server that adds event listeners on every request without removing them.
Output: The AI identifies the orphaned listeners, suggests removeEventListener or using once: true, and shows heap snapshot analysis commands.


3. Optimize Database Queries

Task: Find slow SQL queries and suggest indexes or rewrites.

Prompt:

You are a DBA. Review the following SQL query that runs frequently on a PostgreSQL database with 10 million rows. Provide an execution plan analysis, suggest missing indexes, and rewrite the query to reduce execution time by at least 50%. Use EXPLAIN ANALYZE output if available.

[Paste your SQL query here]

Example:
Input: SELECT * FROM orders WHERE customer_id = 123 AND status = 'pending'; without indexes.
Output: The AI suggests a composite index on (customer_id, status), shows a query rewrite using a covering index, and estimates a reduction from 5 seconds to 10 milliseconds.


4. Reduce Bundle Size

Task: Identify large dependencies and tree-shaking opportunities.

Prompt:

Analyze the following webpack/bundler configuration and import statements. List the top 5 modules that contribute most to bundle size. Suggest replacements with smaller libraries (e.g., lodash vs lodash-es), code splitting points, and dead code elimination techniques.

[Paste your webpack.config.js and entry file here]

Example:
Input: A React app importing the entire lodash library.
Output: The AI suggests importing only lodash.debounce, adds splitChunks config, and shows a size reduction from 400 KB to 50 KB.


5. Improve Rendering Performance

Task: Find layout thrashing and repaint issues in frontend code.

Prompt:

Review the following React component for performance issues. Identify any unnecessary re-renders, expensive calculations in render, or direct DOM manipulations that cause layout thrashing. Provide fixes using React.memo, useMemo, useCallback, or CSS containment.

[Paste your React component code here]

Example:
Input: A list component that re-renders all items on every keystroke.
Output: The AI wraps the list item in React.memo, moves a filter function to useMemo, and reports a 70% reduction in render time.


6. Find I/O Bottlenecks

Task: Identify slow file or network operations.

Prompt:

Analyze the following Python async code for I/O performance issues. Highlight any blocking calls (e.g., time.sleep, requests.get) that could be replaced with async versions. Provide a refactored version using asyncio and aiohttp, and estimate the speedup for 100 concurrent requests.

[Paste your async code here]

Example:
Input: A script using requests.get inside a loop.
Output: The AI replaces it with aiohttp.ClientSession, adds asyncio.gather, and shows a 10x throughput improvement.


7. Spot Algorithmic Inefficiencies

Task: Detect O(n²) or worse algorithms.

Prompt:

You are a computer science professor. Review the following code and find any algorithms with suboptimal time complexity (e.g., nested loops over large arrays). Suggest a more efficient algorithm (e.g., using hash maps, binary search, or divide-and-conquer). Provide Big-O analysis and before/after complexity.

[Paste your code here]

Example:
Input: Two nested loops checking duplicates in an array of 100,000 elements.
Output: The AI replaces it with a Set-based solution, reducing complexity from O(n²) to O(n), and shows a runtime drop from 10 seconds to 0.1 seconds.


8. Optimize API Payloads

Task: Reduce response size and network latency.

Prompt:

Review the following REST API endpoint (Node.js + Express). Suggest ways to reduce the response payload size: field selection, pagination, compression (gzip/brotli), and caching headers. Provide code examples for each optimization, and calculate the estimated bandwidth savings for 1 million requests per day.

[Paste your route handler code here]

Example:
Input: An endpoint returning the entire user object (100 fields) when only name and email are needed.
Output: The AI adds query parameter ?fields=name,email, enables compression middleware, and estimates 80% bandwidth reduction.


9. Detect Thread Contention

Task: Find race conditions or lock bottlenecks in multi-threaded code.

Prompt:

Analyze the following Java concurrent code for thread contention. Identify any synchronized blocks that could be replaced with `ReentrantLock`, `StampedLock`, or `ConcurrentHashMap`. Provide a refactored version with reduced lock granularity, and estimate the throughput improvement under 100 threads.

[Paste your Java code here]

Example:
Input: A method that synchronizes on a large HashMap.
Output: The AI replaces it with ConcurrentHashMap, removes the synchronized block, and shows a 5x throughput increase.


10. Lazy Load Resources

Task: Delay loading of non-critical resources until needed.

Prompt:

You are a web performance consultant. Given the following HTML page, identify which resources can be lazy-loaded (images, scripts, iframes). Provide modified HTML using `loading="lazy"`, `defer`, and `Intersection Observer` for custom components. Include a Lighthouse audit expectation.

[Paste your HTML here]

Example:
Input: A page with 20 images and 5 scripts all loaded eagerly.
Output: The AI adds loading="lazy" to images below the fold, defer to scripts, and predicts a 40% improvement in Largest Contentful Paint (LCP).


11. Reduce Function Call Overhead

Task: Minimize the cost of frequent small function calls.

Prompt:

Review the following Python code that calls a small utility function millions of times in a loop. Determine if inlining the function, using `@lru_cache`, or switching to a native implementation (e.g., `map`, `numpy`) would improve performance. Provide benchmarks with timeit.

[Paste your code here]

Example:
Input: A loop calling math.sqrt() on each element.
Output: The AI replaces it with numpy.sqrt(array), showing a 100x speedup due to vectorization.


12. Optimize Search Algorithms

Task: Improve search performance in large datasets.

Prompt:

You are a search engineer. The following code performs a linear search over a sorted array of 1 million integers. Suggest a more efficient search algorithm (e.g., binary search, interpolation search, or using a `bisect` module). Provide code and a complexity comparison.

[Paste your search code here]

Example:
Input: A for loop with if arr[i] == target.
Output: The AI implements bisect_left, reducing average comparisons from 500,000 to 20.


13. Cache Repeated Computations

Task: Eliminate redundant calculations.

Prompt:

Analyze the following code and identify any repeated computations that could be cached. Suggest using memoization (e.g., `functools.lru_cache` in Python, `useMemo` in React) or a custom cache with TTL. Provide before/after code and show the expected reduction in execution time.

[Paste your code here]

Example:
Input: A recursive Fibonacci function without cache.
Output: The AI adds @lru_cache(maxsize=None), reducing time from exponential to linear.


14. Improve Data Structure Choice

Task: Select the optimal data structure for the workload.

Prompt:

Review the following code that frequently inserts and searches in a collection of 100,000 items. Currently using a list. Suggest a more appropriate data structure (e.g., set, dict, heap, or tree) and explain the time complexity difference. Provide a refactored version.

[Paste your code here]

Example:
Input: A list used for membership checks (if x in list).
Output: The AI replaces it with a set, reducing lookup complexity from O(n) to O(1).


15. Profile Memory Usage in Detail

Task: Get a detailed memory breakdown by object type.

Prompt:

You are a memory profiling expert. Given the following Python script, use `tracemalloc` or `memory_profiler` to identify which objects consume the most memory. Provide code to log memory snapshots and suggest specific optimizations (e.g., using generators instead of lists, recycling objects).

[Paste your script here]

Example:
Input: A script that loads a large CSV file into a list of dictionaries.
Output: The AI suggests using pandas.read_csv with chunksize, reducing peak memory from 500 MB to 10 MB.


16. Optimize CSS for Rendering

Task: Reduce style recalculation time.

Prompt:

You are a CSS performance specialist. Review the following CSS and HTML structure. Identify selectors that cause style recalculations (e.g., universal selectors, deeply nested rules). Suggest replacing them with class-based selectors, using `will-change` wisely, and avoiding expensive properties like `box-shadow` on many elements. Provide a before/after rendering timeline.

[Paste your CSS and HTML here]

Example:
Input: A page using div * { margin: 0; }.
Output: The AI replaces it with a reset classes, reducing style recalculation time by 50%.


17. Parallelize Independent Tasks

Task: Speed up batch processing by running tasks concurrently.

Prompt:

The following code processes 10,000 files sequentially. Identify which tasks are I/O-bound vs CPU-bound, and suggest a parallelization strategy: `ThreadPoolExecutor` for I/O, `ProcessPoolExecutor` for CPU, or `asyncio` for network. Provide a refactored version with `concurrent.futures`.

[Paste your sequential code here]

Example:
Input: A loop reading 10,000 files one by one.
Output: The AI uses ThreadPoolExecutor(max_workers=8), reducing total time from 100 seconds to 15 seconds.


18. Analyze Crit Path in Web App

Task: Identify what blocks the critical rendering path.

Prompt:

You are a web performance auditor. Given the following HTML, CSS, and JS files, analyze the critical rendering path. Identify render-blocking resources (e.g., CSS and JS without `async`/`defer`). Suggest inlining critical CSS, deferring non-critical JS, and preloading key assets. Provide a performance budget.

[Paste your files here]

Example:
Input: A page with 3 CSS files and 5 JS files loaded in <head>.
Output: The AI inlines critical CSS, adds defer to JS, and reports a 60% reduction in First Meaningful Paint.


Conclusion

Performance optimization doesn't have to be guesswork. By using these eighteen prompts, you can systematically profile, diagnose, and fix bottlenecks in your code. Start with the prompt that matches your biggest pain point — whether it's slow database queries, bloated bundles, or CPU-heavy functions. Each prompt gives you a concrete action plan with code examples you can apply immediately. Bookmark this page and use it as your go-to reference whenever you need to make your code faster. If you have a specific performance challenge not covered here, drop a comment below — we might add it to the next edition!

← All posts

Comments