Introduction
Performance optimization is a critical skill for any developer. Even the most elegant code can become a bottleneck under load, leading to slow response times, high server costs, and poor user experience. According to a 2023 study by Google, 53% of mobile users abandon a site that takes longer than three seconds to load. Yet many developers rely on intuition rather than data-driven profiling to find and fix performance issues.
This article provides ten ready-to-use prompts for working with AI assistants to identify bottlenecks, optimize algorithms, reduce memory usage, and improve overall code efficiency. Each prompt is designed to be copy-pasted into any modern LLM (like GPT-4, Claude, or Gemini) and includes a practical example.
Why Use Prompts for Performance Work?
AI assistants can analyze code patterns, suggest alternatives, and even generate benchmark tests. But vague prompts like "optimize this code" yield vague results. Specific prompts that include context (language, constraints, profiling data) produce actionable advice. For instance, a prompt that says "Find the slowest function in this Python script using cProfile output" is far more useful than "Make this faster."
The 10 Prompts
1. Profile My Code for Bottlenecks
Task: Identify the most time-consuming parts of your code.
Prompt:
I have a Python script that processes a list of 10,000 user records. Here is the code:
[PASTE CODE]
Please analyze it and tell me:
1. Which function is likely the slowest?
2. What is the time complexity of each major function?
3. Suggest one profiling tool I should use (e.g., cProfile, line_profiler).
Example: A developer used this prompt with a data-cleaning function and discovered that a nested loop with O(n²) complexity was processing 10,000 records in 45 seconds. The AI suggested converting it to a dictionary lookup, reducing runtime to 0.2 seconds.
2. Optimize a Database Query
Task: Improve slow SQL queries.
Prompt:
I have a PostgreSQL query that takes 12 seconds to run on a table with 5 million rows. Here is the query:
SELECT * FROM orders WHERE customer_id = 12345 AND status = 'active' ORDER BY created_at DESC;
Explain:
1. Which index would help most?
2. Rewrite the query to use a covering index.
3. Show the EXPLAIN ANALYZE output you expect.
Example: The AI suggested a composite index on (customer_id, status, created_at DESC). After applying it, query time dropped to 0.8 seconds.
3. Reduce Memory Usage in Python
Task: Find memory leaks or inefficient data structures.
Prompt:
Here is a Python script that loads a 2GB CSV file into memory and crashes. The code:
[PASTE CODE]
Please:
1. Identify the data structures that use the most memory.
2. Suggest a streaming approach (e.g., using pandas chunksize or generators).
3. Show a code rewrite that uses less than 500MB of RAM.
Example: The original script used pd.read_csv() without chunking. The AI rewrote it to process 100,000 rows at a time, reducing peak memory from 2.5GB to 180MB.
4. Optimize Frontend JavaScript Bundle
Task: Reduce bundle size and improve load time.
Prompt:
My React app has a production bundle of 3.2MB. Here is the webpack.config.js:
[PASTE CONFIG]
Suggest:
1. Which packages could be tree-shaken?
2. Should I use dynamic imports? For which components?
3. Show a revised config with code splitting and compression.
Example: The AI identified that moment.js (500KB) was only used for one date format. Replacing it with date-fns reduced the bundle to 2.1MB.
5. Parallelize a CPU-Bound Task
Task: Speed up computation-heavy code using multiprocessing.
Prompt:
I have a function that processes images: resize, apply filter, save. It runs sequentially and takes 8 seconds for 100 images. Here is the code:
[PASTE CODE]
Show how to parallelize it using:
1. Python's multiprocessing.Pool
2. concurrent.futures.ProcessPoolExecutor
3. Explain when multiprocessing is better than threading.
Example: Using a pool of 4 workers, the runtime dropped to 2.5 seconds.
6. Analyze a Slow API Endpoint
Task: Find why an API call takes too long.
Prompt:
My Django REST API endpoint '/api/products' returns 500 products with full details. It takes 3.5 seconds. Here is the view and serializer:
[PASTE CODE]
Please:
1. Identify N+1 queries using Django ORM.
2. Suggest select_related or prefetch_related.
3. Show optimized code with pagination.
Example: The AI found that the serializer fetched related categories and tags with separate queries for each product. Adding prefetch_related('tags', 'category') reduced the time to 0.4 seconds.
7. Optimize a Heavy Loop in C
Task: Speed up a loop that processes millions of items.
Prompt:
Here is a C# method that sums values from a list of 10 million integers:
public long Sum(List<int> numbers) {
long total = 0;
for (int i = 0; i < numbers.Count; i++) {
total += numbers[i];
}
return total;
}
Suggest:
1. Use of Span<T> or unsafe code for speed.
2. SIMD vectorization with System.Numerics.
3. Benchmark the alternatives.
Example: Using Vector<long> from System.Numerics, the loop ran 4x faster.
8. Find Inefficient Regular Expressions
Task: Improve regex that causes catastrophic backtracking.
Prompt:
This regex causes a timeout on input strings longer than 100 characters:
^(a+)+$
Explain:
1. Why does this cause catastrophic backtracking?
2. Rewrite it to be linear (O(n)).
3. Show how to test with a timeout in Python.
Example: The AI replaced it with ^(a+)$ and added re.match with a timeout using signal.
9. Optimize Image Loading on a Website
Task: Improve Largest Contentful Paint (LCP) score.
Prompt:
My webpage loads a 2MB hero image. The LCP score is 4.2 seconds. Here is the HTML:
<img src="hero.jpg" alt="Hero">
Suggest:
1. Use of next-gen formats (WebP, AVIF).
2. Lazy loading and responsive images with srcset.
3. Show the optimized HTML and CSS.
Example: Converting to WebP, using 800px and 1600px versions, and adding loading="lazy" improved LCP to 1.8 seconds.
10. Benchmark Two Algorithms
Task: Compare performance of different implementations.
Prompt:
I need to sort 1 million integers. I have two implementations: quicksort and Python's built-in sorted(). Here is my code:
[PASTE CODE]
Write a benchmark using timeit that:
1. Runs each 10 times and reports mean and standard deviation.
2. Tests with random, sorted, and reversed data.
3. Visualizes the results in a table.
Example: The benchmark showed that built-in sorted() is 20x faster than the custom quicksort due to C-level implementation.
Best Practices for Using Performance Prompts
- Always include profiling data. The more specific the numbers, the better the advice. Use tools like cProfile, Chrome DevTools, or Django Debug Toolbar.
- Test before and after. Use
timeitfor Python,BenchmarkDotNetfor C#, orhyperfinefor any CLI tool. - Focus on the 20% that matters. The Pareto principle applies: 80% of performance gains come from 20% of the code.
- Avoid premature optimization. Measure first, then optimize only where needed.
Conclusion
Performance optimization doesn't have to be guesswork. By using structured prompts with AI assistants, you can quickly identify bottlenecks, test alternatives, and implement proven solutions. Start with profiling, ask specific questions, and always verify with benchmarks. The ten prompts above cover the most common scenarios — from database queries to frontend bundles. Bookmark this guide and apply them to your next project.
Remember: the goal is not perfect code, but code that is fast enough for your users and efficient enough for your infrastructure.
Comments