Finds and fixes game frame-rate problems by measurement in Godot, Unity, Unreal or Roblox: CPU- vs GPU-bound, then the biggest fix (draw calls, pooling, GC…
Performance optimization
The loop: set a budget, measure, find the one bottleneck, fix it, measure again, report the
numbers. Guesses usually target the wrong system, so nothing changes until a profiler or a
frame-time capture says where the time goes. This skill is the cross-engine method and the
fixes that recur; each engine's profiler is listed below and in the reference.
When to use
The frame rate is low or uneven, or a target (60 FPS desktop, 30 or 60 on mobile) is missed.
Hitches: first-time effects, loading mid-game, periodic GC pauses, big fights.
Choosing what to optimize, setting budgets, or adding a performance check to CI.
Not this skill: physics stability (physics-tuning), install or download size
(unity-build-size), network latency (roblox-networking, godot-multiplayer), shader maths
(shader-programming).
Core workflow
Turn the complaint into a number. Target FPS gives the budget: 60 FPS is 16.67 ms, 30 is
33.3 ms, 120 is 8.33 ms. Find a repeatable worst-case scene and save it (a test level, a
recorded input, a fixed seed).
Uncap before measuring. VSync and frame caps hide headroom: a 4 ms frame and a 15 ms
frame both show 60 FPS. Godot --disable-vsync (and --max-fps 0); Unity
QualitySettings.vSyncCount = 0 with Application.targetFrameRate = -1 on desktop; Unreal
r.VSync 0 and t.MaxFPS 0. Then read frame time in ms, not FPS.
Profile a release-like build on target hardware. Editor and debug builds add overhead
and skip compiler optimization; use a Godot release export, a Unity Development build with
the profiler attached, or an Unreal Development or Test build.
Split CPU from GPU. Compare main-thread, render-thread and GPU time. The side closest to
the frame time is the bottleneck; fixing the other side changes nothing.
Fix the single biggest cost, preferring doing less work (cache, partition space, run less
often) over polishing a hot line. Then apply the matching fix below.
Re-measure the same scene on the same machine, three runs each, and keep or revert on
the numbers.
Set budgets per subsystem and per asset so the fix stays fixed, and add the frame-time
check to CI where the engine allows it.
Report the scene, hardware, build type, before and after (average and p95 or p99 frame
time), the bottleneck and the fix. Say what was measured headless or in the editor and what
still needs the user's device.
Patterns
1. Frame budget split
@60 FPS = 16.67 ms. The slower of CPU frame and GPU frame sets the frame rate.
Example sub-budgets: gameplay/scripts ~5 ms · physics ~3 ms · render submit ~4 ms · UI ~2 ms · slack.
Mobile: keep 20-30% headroom so the game survives thermal throttling.
2. Where each engine reports the split
Godot 4.7 : Debugger > Profiler (script and physics), Visual Profiler (CPU vs GPU render time
per pass), Monitors (FPS, draw calls, memory, pipeline compilations).
Performance.get_monitor(TIME_PROCESS) is the worst frame of the last second in
SECONDS, refreshed once a second; time frames yourself for per-frame spikes.
Unity 6.3 LTS : Profiler window + Frame Debugger. ProfilerRecorder on "CPU Main Thread Frame Time"
and "GPU Frame Time" (release players need Frame Timing Stats in Player Settings).
Unreal 5.8 : stat unit (Frame / Game / Draw / RHIT / GPU), stat scenerendering (draw calls),
Unreal Insights; `csvprofile frames=600` writes a CSV capture you can read.
Roblox : MicroProfiler (Ctrl+F6 in Studio and the desktop client; mobile via its web UI).
# Game and Draw are CPU threads; GPU is the graphics card. Whichever is nearest Frame wins.
Roblox: profile on a mid-range phone, because a capped desktop hides the problem. With
Studio Assistant, Roblox's built-in rbx-perf-profiling (reads MicroProfiler captures) and
rbx-scene-analysis (rendering cost, memory, leaked instances) give real data; use
roblox-studio-workflow to run checks in Studio, roblox-physics for assembly and simulation
cost, and roblox-networking when "lag" means network delay rather than frame time.
3. Headless CPU frame-time check (Godot)
# tools/frame_stats.gd: CPU frame time of one scene, headless (no GPU work is measured).
# godot --headless --path . --script res://tools/frame_stats.gd -- res://levels/worst.tscn 600 16.6
extends SceneTree
func _initialize() -> void:
var args := OS.get_cmdline_user_args()
var scene_path := args[0] if args.size() > 0 else "res://main.tscn"
var frames := int(args[1]) if args.size() > 1 else 600
var budget_ms := float(args[2]) if args.size() > 2 else 16.6
OS.low_processor_usage_mode_sleep_usec = 0 # headless otherwise sleeps ~6.9 ms a frame
root.add_child(load(scene_path).instantiate())
for i in 60: # skip loading and first-use spikes
await process_frame
var ms := PackedFloat64Array()
var last := Time.get_ticks_usec()
for i in frames:
await process_frame
var now := Time.get_ticks_usec()
ms.append((now - last) / 1000.0) # whole frame: scripts, physics, engine
last = now
ms.sort()
var avg := 0.0
for v in ms:
avg += v / ms.size()
var p95 := ms[int(ms.size() * 0.95)]
var p99 := ms[int(ms.size() * 0.99)]
var over := ms.size() - ms.bsearch(budget_ms, false)
print("FRAME avg=%.2fms p95=%.2fms p99=%.2fms max=%.2fms over_budget=%d/%d"
% [avg, p95, p99, ms[-1], over, ms.size()])
quit(1 if p95 > budget_ms else 0)
It exits 1 when p95 exceeds the budget, so it can gate CI for script and physics cost. Headless
mode has no renderer, so it says nothing about GPU time or draw calls; for those, ask the user to
run the game with --disable-vsync --print-fps or open the Visual Profiler and report the CPU and
GPU ms for the same scene. A shared or busy machine adds noise, so compare runs on one machine.
4. Object pooling (stop allocating and freeing in hot loops)
var _pool: Array[Node2D] = [] # Node3D for 3D; both have `visible`
func acquire() -> Node2D:
var n: Node2D = _pool.pop_back() if not _pool.is_empty() else bullet_scene.instantiate()
n.set_process(true); n.visible = true
return n
func release(n: Node2D) -> void:
n.set_process(false); n.visible = false # disable + hide; don't free
_pool.append(n)
# Pre-warm at load. Also reset velocity, timers and signal connections on release.
5. Cut draw calls and state changes
- Atlas textures and share materials so sprites and meshes batch.
- Identical meshes: GPU instancing (Unity; under URP/HDRP the SRP Batcher or GPU Resident Drawer
takes over), MultiMesh/MultiMeshInstance (Godot), Instanced Static Mesh (Unreal).
- Static geometry: static batching or baking. Bake lighting that does not move.
- Overdraw: fewer large overlapping transparent and particle layers.
- Fill-rate bound: lower render resolution or scale (2x pixel ratio is 4x the pixels).
Measure draw calls and GPU ms before and after; both should drop.
6. Kill per-frame allocations (GC spikes are periodic hitches)
// Unity 6.3 LTS. Steady state should be 0 B "GC Allocated In Frame".
void Update() {
_hits = Physics.RaycastNonAlloc(ray, _hitBuffer); // reuse a preallocated array
for (int i = 0; i < _hits; i++) { /* ... */ }
} // hit order is undefined and a full buffer may miss the nearest hit: size it, sort if needed
// No LINQ, string building or FindObjectsByType in Update. Cache references once.
// GDScript: reuse Arrays/Dictionaries instead of building new ones each _process.
Gotchas
Measuring with VSync on. The frame rate sits at the refresh rate until the frame is
already over budget, so fixes look like they did nothing. Uncap, then read ms.
Reading TIME_PROCESS every frame in Godot. It is the worst frame of the last second,
updated once a second, so per-frame samples repeat one value. Time frames directly.
Shader and pipeline compile hitches the first time an effect, enemy or material appears,
often gone on the second run because the driver cached it. Godot 4.4+: watch the pipeline
compilation monitors, load features early and keep hidden instances of spawned effects in the
scene. Unity 6: trace and warm PSOs with GraphicsStateCollection (experimental) or warm
shader variants on older APIs. Unreal: PSO precaching and a bundled PSO cache.
Thermal throttling on phones: 60 FPS for two minutes, then a drop. Ask the user to run a
15-minute session on the device and report frame time at the start and end; cap the frame rate
and keep headroom.
Unity Android and iOS run at 30 FPS by default (targetFrameRate = -1). Set
Application.targetFrameRate deliberately before calling it a performance problem.
Fixing the wrong side. CPU micro-optimizations do nothing for a GPU-bound frame, and the
reverse.
Instantiate and free in hot loops cause fragmentation and GC spikes. Pool them.
Unity "Enable GPU Instancing" with no effect under URP/HDRP: the SRP Batcher takes
precedence for compatible shaders. Check the Frame Debugger; for many identical meshes use the
GPU Resident Drawer (Forward+, compute-capable APIs, not OpenGL ES).
Deep Profile or editor numbers reported as results. Both distort timings; quote a build.
No budgets. Without per-subsystem ms and asset ceilings, performance regresses quietly.
Optimizing a prototype before it is fun or measured adds complexity that may be thrown away.
References
references/profiling-and-budgets.md: read when you need a per-engine profiler walkthrough,
the CPU-vs-GPU triage steps, a generic pool with prewarm and overflow policy, batching and
instancing rules per engine, allocation rules for C# and GDScript, do-less techniques (LOD,
culling, time-slicing) or starting asset budgets.
Related skills
physics-tuning: fixed-step cost, sleeping bodies, broadphase layers.
shader-programming: per-pixel cost of an effect; godot-shaders for Godot shader compiles.
godot-export, unity-build-pipeline, unreal-packaging: building the release build you
should profile.
procedural-gen, game-ai: common CPU hotspots (generation, pathfinding) to defer or slice.
Version notes
Last verified: 2026-11-11.
Godot 4.7: TIME_PROCESS and TIME_PHYSICS_PROCESS are per-second maxima set in
main/main.cpp; headless sleeps low_processor_usage_mode_sleep_usec per frame
(core/os/os.cpp); CLI --disable-vsync, --max-fps, --print-fps. Pipeline
precompilation and its monitors arrived in 4.4, the shader baker in 4.5
(https://docs.godotengine.org/en/stable/tutorials/performance/pipeline_compilations.html).
The frame-time script was run on 4.7.2 headless.
Unity 6.3: targetFrameRate defaults and the 30 FPS mobile default
(https://docs.unity.com/en-us/engine/6000.3/script-reference/unityengine/application/targetframerate);
GraphicsStateCollection is experimental
(https://docs.unity.com/en-us/engine/6000.3/manual/materials-and-shaders/shaders/shader-troubleshooting/shader-reduce-stalling/shader-prevent-stutter/shader-pso-trace-warming/shader-pso-introduction).
Unreal: PSO precaching (https://dev.epicgames.com/documentation/unreal-engine/pso-precaching-for-unreal-engine);
csvprofile (https://docs.unrealengine.com/4.27/en-US/TestingAndOptimization/PerformanceAndProfiling/CSVProfiler).
Roblox: MicroProfiler shortcuts and mobile web UI
(https://create.roblox.com/docs/performance-optimization/microprofiler.md); built-in
Assistant skills rbx-perf-profiling and rbx-scene-analysis
(https://create.roblox.com/docs/assistant/skills.md).
RenderDoc 1.47 (2026-10-31), Tracy 0.15.0 (2026-11-05), Unity Project Auditor package 3.2.0
(2026-11-03): GitHub releases and the Unity package registry.
38:[don't have the plugin yet? install it then click "run inline in claude" again.
optimize application performance by measuring first, identifying the actual bottleneck (not the assumed one), fixing it, and verifying the fix with fresh measurement. performance work without data is guessing. premature optimization adds complexity that costs more than it gains. use this skill when performance requirements exist in the spec (load time budgets, response time SLAs), users or monitoring report slow behavior, core web vitals scores are below thresholds, you suspect a regression, or you're building features that handle large datasets or high traffic. do not use this skill before you have evidence of a problem.
measurement tools (synthetic):
@lhci/cli in CI) for reproducible regression detectionbundlesize, webpack-bundle-analyzer)measurement tools (real user monitoring, RUM):
web-vitals npm library or similar (onLCP, onINP, onCLS callbacks)backend profiling:
external connections (optional but recommended):
APM_API_KEY, requires read/write scopes on performance metrics)GOOGLE_API_KEY with Read-Only scopes)performance budgets and thresholds (from Core Web Vitals):
establish a baseline with real data using two complementary approaches. do not skip either.
inputs: access to Chrome DevTools or Lighthouse, ability to instrument code, access to production logs or RUM service
synthetic measurement (controlled, reproducible):
real user monitoring (RUM, real conditions):
import { onLCP, onINP, onCLS } from 'web-vitals';
onLCP(metric => console.log('LCP:', metric.value));
onINP(metric => console.log('INP:', metric.value));
onCLS(metric => console.log('CLS:', metric.value));
backend measurement:
console.time('query-name'); await db.query(...); console.timeEnd('query-name');outputs: baseline numbers (LCP, INP, CLS, bundle size, API p95 latency), run-to-run variance for each metric, date and hardware/network conditions, raw trace files or log entries
edge cases:
use the symptom to decide where to look first. this saves time by narrowing the scope.
inputs: baseline metrics, user reports or monitoring alerts, performance traces from step 1
if the symptom is "first page load is slow":
npx bundlesize --config bundlesize.config.json or analyze with webpack-bundle-analyzerif the symptom is "interaction feels sluggish" (form input lag, button click delay, animation jank):
if the symptom is "page after navigation is slow":
if the symptom is "backend/API endpoints are slow":
step 2b: profile backend and database
inputs: access to database query logs, ability to run EXPLAIN ANALYZE, APM data if available
log_min_duration_statement = 0, MySQL slow_query_log = ON with low thresholdEXPLAIN ANALYZE SELECT ...;outputs: identified slowest query with EXPLAIN ANALYZE plan, connection pool state, number of queries per request
if the symptom is "intermittent slowness" (not consistent):
outputs: narrowed scope (frontend, backend, database, external), specific symptom (LCP, INP, bundle size, query latency, etc.), metric to optimize for in the next step
read the data from step 2, not your intuition.
inputs: performance traces, EXPLAIN ANALYZE output, bundle analysis, monitoring data
frontend bottlenecks (common patterns and their signatures):
| symptom | likely cause | how to confirm |
|---|---|---|
| slow LCP | large images, render-blocking CSS/JS, slow server | network waterfall shows large images or JS/CSS before LCP; TTFB is high |
| high CLS | images without dimensions, late-loaded content, font shifts | Performance trace shows layout shifts; images in HTML lack width/height; font swap causes shift |
| poor INP | heavy JavaScript on main thread, large DOM updates | Performance trace shows long tasks (> 50ms) or many small tasks that add up; React DevTools Profiler shows expensive component renders |
| slow initial load | large bundle, many network requests, missing code splitting | bundle > 200KB gzipped; waterfall shows sequential requests that could be parallelized |
backend bottlenecks (common patterns and their signatures):
| symptom | likely cause | how to confirm |
|---|---|---|
| slow single endpoint | N+1 queries, missing index, unoptimized query | query log shows one query per row; EXPLAIN shows Seq Scan where index expected; query is not using an available index |
| all endpoints slow at once | connection pool exhaustion, CPU/memory saturation, cascading timeouts | all endpoints spike together; database shows mostly idle sessions; application CPU/memory is pegged |
| slow intermittently | GC pauses, lock contention, external dependency timeouts | latency graph shows regular spikes; APM shows timeouts to external services; heap grows before spike |
outputs: root cause identified (not guessed), evidence from step 2 that confirms it, metric that will move when it's fixed
fix one thing at a time. do not bundle multiple changes.
inputs: identified bottleneck from step 3, codebase access
backend fixes (each pattern is distinct; apply only the one step 3 identified):
N+1 queries (symptom: one query per row in a loop)
const users = await db.query('SELECT * FROM users'); const posts = users.map(u => db.query('SELECT * FROM posts WHERE user_id = ?', u.id));const users = await db.query('SELECT users.*, posts.* FROM users LEFT JOIN posts ON posts.user_id = users.id;unbounded data fetching (symptom: list endpoints return 10000+ rows)
GET /api/items returns all itemsGET /api/items?limit=50&offset=0 with explicit sort: ORDER BY id ASCqueries that ignore their index (symptom: EXPLAIN shows Seq Scan where you expected an index)
CREATE INDEX ON users(LOWER(email))), is it unused because of a leading wildcard (use trigram index), is the rows= estimate off (run ANALYZE to update statistics, not just add an index)connection pool exhaustion (symptom: all endpoints slow, database shows idle sessions)
pool_size = (connections_per_instance * num_instances) < database_connection_limitmissing caching (symptom: same expensive query or computation runs repeatedly)
frontend fixes (each pattern is distinct; apply only the one step 3 identified):
missing image optimization (symptom: slow LCP, high CLS)
<img> to prevent layout shift<picture> with fallbackfetchpriority="high" on the LCP image to prioritize its downloadloading="lazy" and decoding="async" on below-the-fold imagessrcset and sizes for resolution switching (different image for mobile vs. desktop)<img src="image.jpg" /><picture><source srcset="image.avif" type="image/avif"><source srcset="image.webp" type="image/webp"><img src="image.jpg" width="800" height="600" loading="lazy" decoding="async" /></picture>unnecessary re-renders (symptom: slow INP, component renders on every keystroke)
const App = () => { const config = { key: 'value' }; return <Child config={config} />; }; (config is a new object every render, Child re-renders unnecessarily)const config = { key: 'value' }; const App = () => <Child config={config} />; (config is stable, Child only re-renders if props change)large bundle size (symptom: slow initial load, LCP high)
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));webpack-bundle-analyzer or equivalent; identify large dependencies that could be lazy-loaded or replacedoutputs: code change committed or staged, before-state and after-state of the bottleneck (e.g., "query count 100 -> 1", "bundle size 300KB -> 150KB", "LCP 3.2s -> 2.1s"), ready for measurement in step 4
a fix is a hypothesis until you re-measure the same way.
inputs: baseline measurements from step 1, fixed code from step 4, ability to run the same measurement command under the same conditions
re-measure using the exact same method as step 1:
key rules: