15 Prompts for Code Performance Optimization: Find Bottlenecks and Boost Efficiency

Introduction

Performance optimization is not about premature optimization—it's about identifying and eliminating real bottlenecks that degrade user experience and increase infrastructure costs. According to Google's research, 53% of mobile users abandon a site if it takes longer than three seconds to load (source: Google/SOASTA Research, 2017). While that statistic is from a few years ago, the principle holds: every millisecond matters. However, many developers waste hours guessing where the slowdowns are, instead of using systematic tools and techniques.

This article presents 15 targeted prompts you can use with AI assistants, profiling tools, and your own reasoning to locate performance bottlenecks, optimize algorithms, and write faster code. Each prompt is designed to be a complete, actionable unit—including a task description, the exact prompt you can use, and an example result. Whether you are profiling a Python web service, a JavaScript frontend, or a backend in Go, these prompts cover the most common optimization scenarios.

The prompts are organized into three categories: Basic (for beginners who want quick wins), Advanced (for developers comfortable with profiling and data structures), and Expert (for those dealing with low-level memory, concurrency, and system-level optimization). Each category contains five prompts, totaling 15.

Basic Prompts

1. Identify Slow Functions via Timeit

Task: Determine which function in a Python script takes the most execution time using a simple timing approach.

Prompt: "I have a Python script with functions process_data(), validate_input(), and generate_report(). Use timeit to measure the execution time of each function with 1000 repetitions. Which one is the slowest, and by what factor?"

Example Result: After running timeit, you might find that generate_report() takes 0.45 seconds per call, while process_data() takes 0.02 seconds. That's a 22x difference, indicating that generate_report() is the primary bottleneck. The prompt helps you quickly isolate the culprit without guessing.

2. Optimize a Loop with List Comprehension

Task: Replace an inefficient for loop that creates a list with a faster list comprehension.

Prompt: "Convert the following loop into a list comprehension for performance: result = []; for i in range(1000000): if i % 2 == 0: result.append(i * 2). Show the optimized version and estimate the speed improvement."

Example Result: The optimized version: result = [i * 2 for i in range(1000000) if i % 2 == 0]. In CPython, list comprehensions are roughly 30-50% faster than manual loops with append() because they avoid the overhead of attribute lookup and function calls. The prompt teaches you a simple but effective optimization.

3. Reduce Database Query Count with N+1 Detection

Task: Identify and fix the N+1 query problem in a web application (e.g., Django, Rails, or raw SQL).

Prompt: "I have a Django view that lists all authors and their books. The current code does authors = Author.objects.all(), then in the template calls author.books.all(). This causes N+1 queries. Write a prompt that detects this pattern and suggests using select_related or prefetch_related. Provide the fixed code."

Example Result: The fixed code: authors = Author.objects.prefetch_related('books').all(). This reduces queries from 1 (for authors) + N (for each author's books) to just 2 queries total. The prompt helps you recognize the pattern and apply the appropriate ORM optimization.

4. Cache Repeated Computations with Memoization

Task: Add memoization to a recursive function (e.g., Fibonacci) to avoid redundant calculations.

Prompt: "The Fibonacci function below is extremely slow for n=40 because of repeated recursion: def fib(n): return n if n <= 1 else fib(n-1) + fib(n-2). Suggest a memoization pattern using functools.lru_cache and show the performance improvement for n=40."

Example Result: Using @functools.lru_cache(maxsize=None) on fib, the time for fib(40) drops from ~30 seconds to microseconds. The prompt explains that caching reduces the time complexity from O(2^n) to O(n).

5. Avoid Unnecessary String Concatenation

Task: Optimize string building in a loop by using join() instead of +=.

Prompt: "I have code that builds a large string with result += str(i) inside a loop of 100,000 iterations. Show why this is slow and provide the optimized version using ''.join()."

Example Result: The slow version creates a new string object each iteration (O(n^2) memory copies). Optimized: result = ''.join(str(i) for i in range(100000)). This runs in O(n) time and is typically 10-100x faster for large loops. The prompt gives a concrete before-and-after.

Advanced Prompts

6. Profile Python Code with cProfile and Visualize

Task: Use cProfile to profile a script and identify the top 5 functions by cumulative time.

Prompt: "Run python -m cProfile -o output.prof my_script.py and then use pstats to print the top 5 functions by cumulative time. Explain how to interpret the output and what 'cumtime' means. Also suggest a tool like SnakeViz to visualize the profile."

Example Result: The output shows function_A with cumtime=2.3s, function_B with cumtime=1.8s, etc. The prompt helps you understand that a high cumtime means the function and all its callees take significant time. Using SnakeViz, you can see a flame graph revealing that a deep call to data_parsing is the real issue.

7. Optimize Memory Usage with Generators

Task: Replace a list that holds millions of items with a generator to reduce memory footprint.

Prompt: "I have a list comprehension that creates 10 million integers: large_list = [x for x in range(10_000_000)]. This uses about 80 MB of RAM. Convert it to a generator and explain the memory savings. Also show how to iterate over it correctly."

Example Result: The generator version: large_gen = (x for x in range(10_000_000)). Memory usage drops to near zero (only the generator object overhead). The prompt clarifies that generators produce items on the fly and are ideal for large data streams.

8. Find Bottlenecks in SQL Queries with EXPLAIN

Task: Analyze a slow SQL query using EXPLAIN ANALYZE to identify missing indexes or full table scans.

Prompt: "I have a query SELECT * FROM orders WHERE customer_id = 12345 AND order_date > '2025-01-01' that takes 3 seconds. Use EXPLAIN ANALYZE to find the bottleneck. What indexes would you add? Provide the exact index creation command."

Example Result: The EXPLAIN ANALYZE output shows a sequential scan on orders (cost=1000..50000). Adding a composite index: CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date);. After adding it, the query time drops to 10 ms. The prompt teaches systematic query optimization.

9. Parallelize CPU-Bound Tasks with multiprocessing

Task: Speed up a CPU-intensive calculation by distributing work across multiple CPU cores.

Prompt: "I have a function compute(x) that does heavy number crunching. I need to call it 1000 times. Currently I use a single for loop. Show how to parallelize it using multiprocessing.Pool and explain the trade-offs (e.g., overhead for small tasks)."

Example Result: Using with Pool(4) as p: results = p.map(compute, range(1000)) can speed up the task by roughly the number of cores (assuming no I/O bottlenecks). The prompt warns that for very small tasks, the overhead of spawning processes may negate the benefit—so use a chunk size.

10. Reduce JavaScript DOM Reflows with Batch Updates

Task: Optimize front-end performance by minimizing layout reflows when updating multiple DOM elements.

Prompt: "I have a loop that updates 1000 DOM elements one by one with element.style.width = newWidth + 'px'. This causes 1000 reflows. Show how to batch updates using requestAnimationFrame or document fragments, and explain the performance gain."

Example Result: By wrapping all changes in a requestAnimationFrame callback, or by using a document fragment to build the HTML and then appending it once, the number of reflows drops to 1. Typical improvement: from 200 ms to 10 ms for 1000 elements. The prompt provides a practical front-end fix.

Expert Prompts

11. Analyze Memory Leaks with Heap Profiling

Task: Use a heap profiler (e.g., Python's tracemalloc or Node's --inspect) to find objects that are not being garbage collected.

Prompt: "I suspect a memory leak in my long-running Python service. Use tracemalloc to take two snapshots 10 minutes apart and compare them. Show the top 5 allocated object types that increased the most. Then suggest how to fix a common leak pattern like cyclical references with weakref."

Example Result: The snapshot comparison reveals that Order objects increased by 5000, but they are stored in a global cache that never clears. The fix: use weakref.WeakValueDictionary for the cache. The prompt demonstrates a precise diagnostic workflow.

12. Optimize Go Concurrency with Worker Pools

Task: Limit goroutine creation to avoid overwhelming system resources while processing a large number of tasks.

Prompt: "I have a Go program that spawns 100,000 goroutines to process tasks, causing high memory usage. Show how to implement a worker pool with sync.WaitGroup and a buffered channel to limit concurrency to 10 workers. Explain the memory savings."

Example Result: The worker pool pattern uses a channel of struct{} as a semaphore. Memory usage drops from 2 GB to 200 MB because only 10 goroutines exist simultaneously. The prompt teaches idiomatic Go concurrency control.

13. Use SIMD Instructions for Data-Level Parallelism

Task: Speed up numerical computations by leveraging Single Instruction Multiple Data (SIMD) via compiler intrinsics or libraries.

Prompt: "I have a loop that adds two arrays of 1 million floats. In C, this is a simple for loop. Show how to use Intel SSE/AVX intrinsics to process 4 or 8 floats per instruction. Provide the code and estimate the speedup."

Example Result: Using _mm256_add_ps to process 8 floats at once, the loop speed increases about 4x on a modern CPU (limited by memory bandwidth). The prompt includes example C code with #include <immintrin.h> and explains alignment requirements.

14. Reduce Lock Contention with Read-Write Locks

Task: Optimize a multithreaded application where a shared data structure is read frequently but written rarely.

Prompt: "I have a Python program using threading.Lock protecting a dictionary. Reads are 95% of operations, writes 5%. Show how to replace the lock with threading.RLock or readerwriterlock to allow concurrent reads. Measure the improvement."

Example Result: Using a read-write lock (rwlock.RWLockFair), read operations no longer block each other. Throughput for a 10-thread workload increases by 300% because reads can proceed in parallel. The prompt explains the trade-off: writers still block all readers.

15. Profile Rust Code with perf and Flamegraphs

Task: Identify the hottest function in a Rust binary using Linux perf and generate a flamegraph.

Prompt: "I have a Rust binary my_app. Run perf record --call-graph dwarf ./my_app, then `perf script

| stackcollapse-perf.pl | flamegraph.pl > flame.svg`. Explain how to interpret the flamegraph and find the function taking the most CPU time (the widest top bar)."

Example Result: The flamegraph shows that parse_json accounts for 60% of CPU time. The prompt suggests using a faster JSON parser like simd-json or manually optimizing the parsing logic. This is a standard expert-level profiling workflow.

Conclusion

Performance optimization is a skill that combines systematic measurement with targeted fixes. The 15 prompts above cover a spectrum from simple loop optimizations to advanced concurrency and SIMD techniques. The key takeaway is: never optimize without profiling. Use tools like cProfile, EXPLAIN ANALYZE, perf, and heap profilers to find the real bottlenecks—your intuition is often wrong.

Start with the basic prompts if you are new to optimization. As you gain confidence, move to the advanced and expert prompts. Each prompt is a reusable pattern you can adapt to your own codebase. The next time a page loads slowly or a batch job takes hours, you now have a structured approach to diagnose and fix it.

What's your biggest performance challenge right now? Try one of these prompts and share your results in the comments. Optimize deliberately, not prematurely.

← All posts

Comments