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

Is your application slow? Before you randomly tweak code, you need a systematic approach. AI assistants can act as a senior performance engineer on demand — if you know how to ask. This collection of 12 prompts is designed to help you find bottlenecks and fix them with the same heuristics used at companies like Google and Netflix. All examples are based on official documentation and real-world practice.

1. Profile First, Guess Later

When to use: When you want to know exactly where time is spent instead of guessing.

Prompt:

Act as a performance engineer. I have a [language] project. Recommend the best profiler for [platform], explain how to run it, and show me how to interpret the top 5 hot functions. Provide a command-line example.

Example: For a Python service, the answer will suggest cProfile (python -m cProfile -s time myscript.py) and point out that most time is spent in time.sleep or database calls. Per the Python profiler docs, you should look for functions with high cumulative time, not just high tottime.

2. Detect N+1 Queries Instantly

When to use: When a page load runs hundreds of SQL queries.

Prompt:

Here is an ORM query in [language/framework]: [code]. It is slow because of an N+1 pattern. Show me how to eager-load all related records with a single query, and explain what happens under the hood.

Example: A Rails model with `posts.each {

|p| p.comments }— the AI will suggestincludes(:comments)` and show that this reduces 101 queries to 2. This matches the ActiveRecord documentation on eager loading.

3. Refactor a Hot Loop

When to use: When a loop over large data is a bottleneck.

Prompt:

Read this loop in [language]: [code]. It is called 10 million times. Optimize it using vectorization or a better data structure. Keep the semantics identical and provide a benchmark.

Example: A Python loop that sums squares of large arrays gets replaced by sum(x*x for x in arr) or numpy.square(arr).sum(). According to the NumPy docs, vectorized operations are often an order of magnitude faster than pure Python loops.

4. Optimize Memory with Caching

When to use: When you see high memory usage or repeated expensive computations.

Prompt:

My service caches results of [function]. Propose a caching pattern (cache-aside, write-through, or TTL) with code. Explain cache invalidation and how to avoid staleness. Use [Redis] as a backend.

Example: The AI may show a cache-aside implementation where the cache is checked first, on miss the data is loaded from DB and written back, plus an atomic update script. A real-world case is GitHub's use of caching to reduce database load (documented in their engineering blog).

5. Reduce Bundle Size

When to use: When your frontend JS bundle is too large.

Prompt:

This is my webpack config: [config]. Reduce the bundle size using code splitting, tree shaking, and dependency analysis. Show me the modified config and the expected size reduction.

Example: The AI will suggest mode: 'production', optimization.splitChunks, and import() for lazy loading. According to Google's Web Vitals documentation, reducing bundle size directly improves TBT and LCP.

6. Async I/O Refactoring

When to use: When I/O-bound code runs sequentially.

Prompt:

Refactor this synchronous code to use async/await or threads in [language]: [code]. It makes 100 HTTP calls. Avoid creating too many threads. Explain the trade-offs and any consistency issues.

Example: In JavaScript, Promise.all with concurrency control will replace for-loop await. In Python, asyncio.gather may be offered, but the AI will warn about GIL. A good answer cites the official asyncio docs when I/O latency dominates.

7. Choose the Right Algorithm

When to use: When you suspect algorithmic complexity is the issue.

Prompt:

Compute the Big O complexity of this function: [code]. It becomes slower as input grows. Suggest a different algorithm or data structure and implement it. Show how it changes the complexity.

Example: A nested loop with array lookups might become a HashMap-based solution. The AI may point out that Python's dict has O(1) average lookup (see the TimeComplexity page of python.org) and that changing a linear scan to a set reduces O(n²) to O(n).

8. Database Index Recommendations

When to use: When a query table scan is slow.

Prompt:

Given the table schema [SQL] and this slow query [SQL], recommend indexes. Explain how to verify them with EXPLAIN and what trade-offs additional indexes bring for writes.

Example: The AI will propose CREATE INDEX idx_users_email ON users(email); and note that covering indexes can speed up a query. This is grounded in PostgreSQL's official documentation on indexes.

9. Compiler Flags Tuning

When to use: When you're compiling C/C++/Rust and want max speed.

Prompt:

Show me the best compiler flags for [GCC/Clang] for a release build targeting [CPU]. Explain what each flag does and its side effects. Also mention when `-O3` might not be optimal.

Example: The answer will include -O2 -march=native -flto and warn that -march=native may hurt portability. GCC's manual lists these flags with exact trade-offs.

10. Network Payload Optimization

When to use: When API calls are slow due to large JSON responses.

Prompt:

My API returns a 1 MB JSON response. Suggest ways to reduce this: gzip, pagination, field selection, or a binary format. Show before/after sizes and a code snippet for the best option.

Example: The AI might recommend enabling gzip in Express (compression middleware) and adding pagination with limit/offset. web.dev strongly advises text compression as a core performance fix.

11. Remove Unused Dependencies

When to use: When you want to slim down your project.

Prompt:

Scan my package.json for unused or duplicate dependencies that slow down the build or runtime. Show me the commands to verify (`npm ls`, `depcheck`) and suggest replacements.

Example: The AI may find lodash and suggest using native functional methods for small projects, based on the 'You Might Not Need Lodash' repo. This cuts install time and reduces dependency supply chain.

12. Write a Load Test

When to use: To verify improvements under realistic traffic.

Prompt:

Write a k6 load test for my endpoint [URL] with 100 virtual users, ramp-up over 1 minute, and a threshold that p95 latency is below 500 ms. Explain what the metrics mean.

Example: The AI returns a k6 script with thresholds: { http_req_duration: ['p(95)<500'] } and explains that p95 latency matters more than average because it shows worst-case user experience. k6's documentation defines all metrics.

Use these prompts as a starting point, not a substitute for a profiler. Always verify suggestions with benchmarks. Copy a few into your AI assistant and see what you find — the fastest bottleneck is often one you haven't measured yet.

← All posts

Comments