10 Prompts for Code Performance Optimization: Find Bottlenecks and Speed Up Your Application

10 Prompts for Code Performance Optimization: Find Bottlenecks and Speed Up Your Application

Performance tuning is about measuring, not guessing. These 10 AI prompts help you profile, analyze, and optimize code—without wasting time on random changes. Each prompt includes a real example you can copy and adapt.

Why it matters: A single inefficient query can ruin response times. The classic '90/10 rule' says about 90% of execution time is spent in 10% of the code. Profiling finds that 10%—and these prompts show you how.

1. Act as a Performance Profiler

Prompt: 'Act as a performance profiler. Here's a function that processes a list of orders. Profile it using cProfile, identify the top 3 bottlenecks, and suggest concrete optimizations. Return your analysis as a markdown report with a table.'

Why: It forces the AI to use a structured approach with profiling output.

Example:

import cProfile, pstats
def process_orders(orders):
    total = 0
    for order in orders:
        total += sum(order['items'])
    return total
cProfile.run('process_orders(orders)', 'profile.out')
pstats.Stats('profile.out').sort_stats('cumulative').print_stats(10)

The AI will flag the sum() call inside the loop and suggest using itertools.chain or
a generator expression to avoid repeated summation:

from itertools import chain

def process_orders(orders):
    return sum(chain.from_iterable(order['items'] for order in orders))

That small change turns an O(n×m) loop into a single pass over all items, and the profiler output will confirm the improvement. The key takeaway: always ask for the profiling evidence first, then the fix.


2. Hunt Down N+1 Queries in Database Code

Prompt: 'Act as a database performance expert. This ORM code fetches a list of authors and their books. It runs one query per author. Rewrite it to use eager loading or a single JOIN, and explain why the N+1 pattern is slow. Provide before/after code.'

Why: N+1 queries are the #1 cause of API slowness in web applications. The AI will show you how to batch your database calls.

Example:

# Before
for author in Author.objects.all():
    books = author.books.all()  # One query per author

# After
authors = Author.objects.prefetch_related('books')
for author in authors:
    books = author.books.all()

The prompt forces the AI to analyze the query count and explain the difference between 1 query + 1 per row vs. 2 total queries.


3. Replace Recursion with an Iterative Approach

Prompt: 'Here's a recursive Fibonacci function. Convert it to an iterative version with dynamic programming. Then compare the time complexity of both and show a benchmark chart with timings for n=10, 20, 30, 40.'

Why: Recursion is elegant but often exponential. AI can generate a memoized or iterative solution and prove it with numbers.

Example:

def fib_recursive(n):
    if n <= 1:
        return n
    return fib_recursive(n-1) + fib_recursive(n-2)

def fib_iterative(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Ask the AI to profile both versions and you'll get a clear recommendation for the iterative version.


4. Optimize a Numpy/Pandas Data Processing Pipeline

Prompt: 'This pandas script processes a 10-million-row DataFrame and runs in 30 seconds. Profile it, identify vectorization opportunities, and rewrite it using vectorized operations instead of apply or iterrows. Show the execution time improvement.'

Why: Pandas apply is notoriously slow. The AI will teach you to think in arrays, not loops.

Example:

# Before
df['total'] = df.apply(lambda row: row['price'] * row['quantity'], axis=1)

# After
df['total'] = df['price'] * df['quantity']

A simple vectorized multiplication is often 100x faster. The AI can also suggest using numba for even more complex logic.


5. Detect Memory Leaks and Excessive Allocations

Prompt: 'Act as a memory profiler. Use tracemalloc to analyze this Python service that processes large JSON files. Find the top 3 memory allocations and identify where memory is being retained. Suggest code changes to reduce memory usage by at least 40%.'

Why: Performance isn't just about speed—memory leaks can cause OOM crashes. This prompt gives you a clear diagnosis.

Example:

import tracemalloc
tracemalloc.start()

# Your code here
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
    print(stat)

The AI will spot patterns like slicing large lists, storing duplicate data, or missing del statements.


6. Reduce Big-O Complexity of an Algorithm

Prompt: 'This function finds duplicates in a list by using a nested loop. Rewrite it to run in O(n) time using a hash set. Explain the trade-off between time and space complexity, and provide a benchmark comparing O(n²) vs O(n) for a list of 100k elements.'

Why: This teaches algorithmic thinking. The AI will show you how to jump from quadratic to linear scaling.

Example:

# Before
def find_duplicates(nums):
    dups = []
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] == nums[j]:
                dups.append(nums[i])
    return dups

# After
def find_duplicates(nums):
    seen, dups = set(), []
    for n in nums:
        if n in seen:
            dups.append(n)
        seen.add(n)
    return dups

The prompt can also ask for a collections.Counter alternative.


7. Optimize DOM Manipulation for Frontend Apps

Prompt: 'This JavaScript function updates a list of 1,000 items on every keystroke, causing lag. Rewrite it using document fragments, debouncing, and batching DOM updates. Explain why direct DOM manipulation is slow and how virtual DOM frameworks solve it.'

Why: Frontend performance matters. The AI will give you a concrete technique to reduce layout thrashing.

Example:

// Before
input.addEventListener('input', () => {
  const results = filterData(input.value);
  const list = document.getElementById('list');
  list.innerHTML = '';
  results.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item;
    list.appendChild(li);
  });
});

The AI will suggest creating a single DocumentFragment and appending it once, plus a debounce utility.


8. Refactor Blocking Sync Code to Async/Await

Prompt: 'This Node.js endpoint blocks the event loop while it reads a large file and processes it. Rewrite it to use async/await, streams, or worker threads. Explain why blocking the event loop is critical and show the difference in latency under load.'

Why: Async patterns keep your service responsive. The AI will show you how to keep the CPU from stalling.

Example:

// Before
app.get('/data', (req, res) => {
  const file = fs.readFileSync('big.json');
  res.json(JSON.parse(file));
});

The AI might suggest using fs.promises.readFile or streaming with createReadStream.


9. Diagnose and Fix Cold Start in Serverless Functions

Prompt: 'Act as a cloud performance architect. This AWS Lambda function takes 4 seconds to start because it initializes a heavy SDK client at every invocation. Show me how to use Lambda layers, environment variables, and global scope to reduce cold starts by switching to Python with a lighter HTTP client.'

Why: Cold starts kill user experience. This prompt teaches you to optimize deployment patterns.

Example:

# Before
def handler(event, context):
    import boto3  # expensive import per call
    client = boto3.client('s3')
    return 'ok'

The AI will move the import and client initialization outside the handler and suggest using httpx instead of the full SDK.


10. Parallelize I/O-Bound Tasks with Concurrency

Prompt: 'This Python script downloads 1,000 URLs sequentially. Rewrite it to use concurrent.futures ThreadPoolExecutor with a max of 20 workers. Then compare the wall time between sequential and concurrent versions. Also warn about GIL limitations and when multiprocessing would be better.'

Why: I/O-bound tasks are a perfect fit for threading. The AI will explain the difference between CPU-bound and I/O-bound.

Example:

# Before
for url in urls:
    requests.get(url)

# After
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=20) as executor:
    list(executor.map(requests.get, urls))

The AI will also suggest using asyncio for a more scalable solution.


Final Tip: Turn These Prompts Into a Habit

Don't just copy the prompts—adapt them to your stack. Always ask the AI to profile first, explain second, and optimize third. That way you're not introducing changes without evidence. And remember: the best optimization is often to delete code you don't need.

Now go find your bottlenecks and speed things up.

← All posts

Comments