You built something with AI that works on your machine, but it takes four seconds to load a page, the database queries stack up, and your hosting bill climbs every week. Optimizing AI-generated code is not about rewriting everything from scratch. It is about knowing where the bottlenecks live, asking your AI assistant the right questions, and applying a repeatable process that turns sluggish prototypes into software people actually want to use.
Photo by Godfrey Atima from Pexels
TL;DR:- AI-generated code ships fast but often skips performance basics like indexing, caching, and efficient queries.
- A structured optimize loop (profile, identify, prompt, verify) catches the worst offenders in hours, not weeks.
- You do not need a CS degree to optimize. You need a profiler, a clear prompt, and a checklist.
Why optimization matters now
Every AI coding tool prioritizes getting something working over getting something fast. Cursor, Claude, Copilot, Lovable, v0: they all produce functional code that solves the immediate problem. None of them spontaneously add database indexes, implement response caching, or batch API calls unless you explicitly ask.
That gap between "it works" and "it works well" is where most AI-built projects stall. Users bounce from slow pages. Server costs balloon. And the builder who shipped a working prototype in a weekend spends the next month firefighting performance issues they do not fully understand.
The good news: optimization follows patterns. The same five or six problems show up in nearly every AI-generated codebase. Once you learn to spot them, fixing them becomes routine.
Common mistakes with AI code
Here are the optimization killers I see most often in AI-built projects:
- N+1 queries: The AI writes a loop that hits the database once per item instead of fetching everything in a single query. A page listing 50 products fires 51 database calls.
- No indexing: Tables grow past a few thousand rows and every query becomes a full table scan. The AI created the schema but never added indexes on columns used in
WHEREclauses. - Uncompressed assets: Images served at original resolution, no lazy loading, no CDN. The AI built the upload feature but skipped the delivery pipeline.
- Redundant re-renders: Frontend frameworks like React re-render entire component trees because the AI did not memoize expensive computations or split components properly.
- Missing caching: Every page load recalculates data that changes once a day. No Redis, no in-memory cache, no HTTP cache headers.
- Synchronous everything: API calls, email sends, and file processing all happen in the request cycle. Users wait for operations that should run in the background.
The optimize loop: step by step
Optimization is not guesswork. It is a four-step loop you repeat until performance hits your target.
Step 1: Profile
Run a profiler or monitoring tool against your app. For web apps, start with your browser's DevTools Network tab and the Lighthouse audit. For backend code, use your framework's built-in query logger or a tool like pg_stat_statements for PostgreSQL.
Write down the three slowest operations. Actual numbers: "Homepage loads in 4.2 seconds. The /api/products endpoint takes 1,800ms. The dashboard query runs 900ms."
Step 2: Identify the root cause
Look at the slow operation and classify it:- Is it a database problem? (slow queries, missing indexes, N+1)
- Is it a network problem? (large payloads, no compression, too many requests)
- Is it a compute problem? (expensive calculations on every request, unoptimized algorithms)
Step 3: Prompt your AI for the fix
This is where working with AI becomes a superpower instead of a liability. Give your AI assistant the specific context:
The /api/products endpoint takes 1,800ms.
Here is the current query: [paste query]
Here is the schema: [paste schema]
The table has 12,000 rows.
Optimize this for sub-200ms response time.
Specific prompts produce specific fixes. Vague prompts like "make my app faster" produce vague advice.
Step 4: Verify
Deploy the fix. Run the same profiler. Compare numbers. If the endpoint dropped from 1,800ms to 180ms, move to the next bottleneck. If it barely changed, the root cause identification was wrong. Go back to Step 2.
"The total output of your team won't go up by 30%, especially in large organizations.">, A Practical Guide on Effective AI Use
This quote applies directly to optimization work. AI will not magically make your entire codebase fast. But targeted, measured optimization on the critical path delivers outsized results.
Tools and workflows that help
You do not need an expensive APM suite to start. Here is what works at each layer:
Frontend profiling:- Chrome DevTools Performance tab and Lighthouse (free, built-in)
web-vitalslibrary for tracking Core Web Vitals in production- Vercel Analytics or Netlify Analytics if you deploy on those platforms
- Framework query loggers (Django Debug Toolbar, Laravel Telescope, Express middleware)
EXPLAIN ANALYZEin PostgreSQL for query plansconsole.time()/console.timeEnd()for quick Node.js timing
pgHerofor PostgreSQL index suggestions- Prisma's
@indexdecorator if you use Prisma ORM - Redis or Upstash for caching frequently accessed data
- Paste slow query + schema into Claude or ChatGPT and ask for index recommendations
- Use Cursor's inline edit to refactor N+1 patterns into batch queries
- Ask your AI to generate a caching layer for endpoints you identify as slow
PERFORMANCE.md file in your repo. Log every optimization you make with before/after numbers. This becomes your playbook for the next project and gives your AI assistant context for future prompts.The following dashboard shows a typical before-and-after snapshot for an AI-built SaaS app after one optimization session targeting the three areas above:
Optimization Results: Example SaaS App
Prompting patterns for optimization
Generic prompts waste tokens and produce generic answers. Here are three prompt templates that consistently produce actionable optimization code:
The Query Optimizer prompt:
Here is my SQL query: [query]
Schema: [schema]
Table sizes: [row counts]
Current execution time: [ms]
Target: under [target]ms
Suggest indexes and query rewrites.
The Bundle Analyzer prompt:
My Next.js bundle is [size]KB.
Here are my imports in [file]: [paste imports]
Which imports are heavy? Suggest lighter alternatives
or dynamic import strategies.
The Caching Strategy prompt:
This endpoint returns [description of data].
Data changes [frequency].
Current response time: [ms].
Suggest a caching strategy with invalidation logic.
Each template forces you to gather real data before prompting. That data-gathering step is itself half the optimization work.
AI Code Optimization Checklist
Your progress is saved automatically in your browser.
FAQ
Frequently Asked Questions
EXPLAIN ANALYZE output means at a basic level: is the database scanning every row, or is it using an index? Your AI assistant can interpret the output for you. Ask it to explain the query plan in plain language and suggest improvements. Over time, you will start reading these plans yourself. The Vibe Coding Bible at vibecodingbible.org covers this workflow in detail for builders without a traditional engineering background.Additional Resources
- A Practical Guide on Effective AI Use - AI as Your Peer ... - Learn how to effectively use AI coding assistants beyond simple prompts. Discover proven workflows, best practices, and strategies. Your rules ...
- Code 100x Faster with AI, Here's How (No Hype, FULL Process) - I'm going to walk you through my full workflow step by step and just get into those nitty-gritty details so you can just copy my process to 10x even 100x your productivity when
- AI Coding Agents: A Practical Guide for Software Developers - A practical guide to working with AI coding agents without the hype. Agents can help write tests, but they often miss edge cases or optimize for passing tests. ...
