Performance optimization
Performance work is a measurement discipline, not a bag of tricks. The method is always the
same: profile → find the one bottleneck → fix that → measure again. This skill teaches that
loop and the highest-leverage fixes (pooling, batching, allocation control, asset budgets), and
points you at each engine's profiler. It pairs with physics-tuning for simulation cost.
When to use
- Use when the frame rate is low or uneven, the game stutters/hitches, or it must hit a target
(60 FPS desktop, 30/60 mobile) and currently doesn't.
- Use to decide what to optimize: profile, read the frame budget, and identify whether the CPU
or GPU is the bottleneck before changing any code.
- Use to apply specific fixes: object pooling, draw-call/batch reduction, removing per-frame
allocations and GC spikes, and setting asset budgets.
When not to use: for physics jitter/tunneling/timestep specifically, use physics-tuning.
For the engine's concrete profiler UI and rendering settings, use that
engine skill (godot-export covers some build settings; engine cores cover the rest). This skill
is the cross-engine method and the shared fixes.
The golden rule: measure first, never guess
Most performance "fixes" applied without profiling target the wrong thing and add complexity for
no gain. Do not optimize code you have not measured. Open the profiler, find the single
biggest cost in a representative scene on representative hardware, and fix that. Re-measure to
confirm the fix helped before moving on. Profile a release/optimized build where it matters —
editor and debug builds lie (editor overhead, no compiler optimization).
Core workflow
- Define the target and reproduce. State the goal (e.g. 60 FPS = 16.67 ms/frame) and find a
repeatable worst-case scene. "Sometimes slow" is unfixable; a reproducible spike is fixable.
- Profile before touching code. Run the engine profiler and read the frame: total frame
time, and the split between CPU (game logic, physics, scripts) and GPU (rendering).
- Find the bottleneck — CPU or GPU. If GPU time ≫ CPU, attack draw calls/overdraw/shaders/
resolution. If CPU time dominates, attack scripts/physics/allocations. Fixing the wrong side
does nothing.
- Fix the single biggest cost. Prefer an algorithmic win (do less work, cache, spatial
partition, run less often) over micro-optimizing a hot line. Apply the matching shared fix
(pooling, batching, allocation removal).
- Re-measure on the same scene/hardware. Confirm the number moved. Keep or revert based on
data, not intuition.
- Set budgets so it stays fixed. Per-frame ms budgets per subsystem, plus asset budgets
(texture sizes, triangle counts, draw-call ceilings); add a perf check to verification.
- Report measured numbers. State before/after frame time, the bottleneck found, and the fix
— never "should be faster". If you could only measure in-editor, say so.
Patterns
1. Frame budget math (turn "feels slow" into a number)
target FPS → frame budget: 60 FPS = 16.67 ms | 30 FPS = 33.3 ms | 120 FPS = 8.33 ms
The WHOLE frame (CPU sim + render submit + GPU) must fit the budget; the GPU runs in parallel,
so the slower of CPU-frame and GPU-frame sets your FPS. Allocate sub-budgets, e.g. @60 FPS:
gameplay/scripts ~5 ms · physics ~3 ms · rendering(CPU submit) ~4 ms · UI/other ~2 ms · slack.
If one subsystem blows its slice, that's your target — not whatever you assumed.
2. Measure with the engine profiler (do this before any fix)
Godot 4.7 : Debugger ▸ Profiler (script/physics time), Visual Profiler (CPU vs GPU render time
per pass) and Monitors tab (FPS, draw calls, memory).
In code: Performance.get_monitor(Performance.TIME_PROCESS) returns SECONDS
(× 1000 for ms); Performance.RENDER_TOTAL_DRAW_CALLS_IN_FRAME for draw calls.
Unity 6.3 LTS : Profiler window (CPU/GPU/Memory/Rendering modules) + Frame Debugger for draw calls.
In code: ProfilerRecorder on "CPU Main Thread Frame Time" / "GPU Frame Time"
(release players need Frame Timing Stats enabled in Player Settings).
Unreal 5.8 : `stat unit` (Frame / Game / Draw / RHIT / GPU ms), `stat fps`,
`stat scenerendering` (draw calls); Unreal Insights for deep traces.
# Read the split: Game = gameplay thread, Draw = render thread (both CPU), GPU = the graphics card.
# Whichever is closest to Frame is the bottleneck; that decides the fix.
3. Object pooling (stop allocating/freeing in hot loops)
# Bullets, particles, enemies, damage numbers: reuse a fixed set instead of instantiate()/free()
# every frame — that thrashes memory and (in C#) feeds the GC.
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) # back to the pool for reuse
# RIGHT: pre-warm the pool at load; reuse. WRONG: instantiate()/queue_free() per shot.
4. Cut draw calls (the most common GPU-side win)
Draw calls and render-state changes (material/shader/texture/blend switches) cost CPU submit time;
thousands of them make the render thread the bottleneck. 2D batchers merge runs of sprites that
share state (most bind several textures per batch), so ordering and atlasing decide the count.
- Atlas textures and share materials so sprites/meshes batch into one call.
- Identical meshes → GPU instancing (Unity; under URP/HDRP the SRP Batcher or GPU Resident Drawer
takes precedence), MultiMesh / MultiMeshInstance (Godot), Instanced Static Mesh (Unreal).
- Static geometry → static batching / baking; mark non-moving objects static.
- Reduce overdraw: limit large overlapping transparent/particle layers (they re-shade pixels).
- If fill rate dominates, lower render resolution: 2× pixel ratio means 4× the pixels of 1×.
For three.js game defaults and warm-up-aware resolution tuning, read `threejs-scene-setup`.
- Fewer real-time lights/shadows; bake lighting where it doesn't move.
Measure draw calls before and after — the count should drop, and so should GPU frame time.
5. Kill per-frame allocations (GC spikes = stutter)
// Unity 6.3 LTS (C#). Allocating every frame fills the managed heap; the GC then stalls a frame.
// WRONG (new array + scene walk every call):
// foreach (var e in FindObjectsByType<Enemy>(FindObjectsSortMode.None)) ... // + LINQ, new[]
// (FindObjectsOfType is obsolete in Unity 6.3; its replacement still allocates.)
// RIGHT: cache references once, reuse buffers, avoid LINQ/boxing in Update.
void Update() {
_hits = Physics.RaycastNonAlloc(ray, _hitBuffer); // reuse a preallocated array
for (int i = 0; i < _hits; i++) { /* ... */ } // no per-frame allocation
} // hit order is undefined and a full buffer may miss the nearest hit: size it, sort if needed
// Godot/GDScript: avoid building new arrays/dictionaries every frame in _process; reuse them.
Pitfalls
- Optimizing without profiling. The intuitive culprit is usually wrong. Measure first, every
time.
- Profiling the editor / a debug build. Editor overhead and unoptimized code mislead. Profile
a release build on target hardware for real numbers.
- Fixing the wrong side. Micro-optimizing CPU code when the GPU is the bottleneck (or vice
versa) changes nothing. Check the CPU-vs-GPU split first.
- Micro-optimizing over algorithm. Shaving a function when an O(n²) loop or a per-frame
full-scene query is the real cost. Reduce the work, don't polish it.
- Instantiate/free in hot loops. Spawning and destroying bullets/particles every frame causes
fragmentation and GC spikes. Pool them.
- Per-frame allocations / LINQ / boxing in
Update (C#) feed the GC → periodic hitches.
Cache and reuse.
- Draw-call explosion from unique materials and unbatched sprites/meshes. Atlas, share
materials, instance, batch.
- 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).
- Overdraw from stacked transparents/particles/full-screen effects re-shading pixels.
- No budgets. Without per-subsystem ms and asset ceilings, performance silently regresses;
enforce them in your build/CI checks.
- Optimizing too early. Don't contort a prototype for performance before it's fun or measured.
References
- For per-engine profiler walkthroughs, the CPU-vs-GPU triage flowchart, a complete pooling
manager, batching/instancing rules per engine, allocation/GC guidance, LOD/culling, and asset
budgets (texture sizes, triangle counts, audio, mobile thermals), read
references/profiling-and-budgets.md.
Related skills
physics-tuning — simulation cost, fixed-step budget, sleeping bodies, broadphase layers.
godot-export — release/build settings that affect measured performance.
procedural-gen, game-ai — common CPU hotspots (generation, pathfinding) to budget and defer.
roguelike, tower-defense, survival-crafting — entity-heavy genres that need pooling/budgets.
1---2name: performance-optimization3description: >4 Find and fix game performance problems methodically — measure with the engine profiler first,5 reason about the frame-time budget, locate the CPU-vs-GPU bottleneck, then apply the right fix:6 object pooling, draw-call batching, fewer allocations/GC spikes, and asset budgets. Engine-7 neutral method that pairs with each engine's profiler. Use when the user mentions performance,8 optimize, low/dropping FPS, frame drops, stutter, lag, profiler, frame budget, draw calls,9 batching, garbage collection/GC spikes, object pooling, or "the game runs slow".10metadata:11 source: https://skillmd.com/skills/junmystery/performance-optimization12---1314# Performance optimization1516Performance work is a measurement discipline, not a bag of tricks. The method is always the17same: **profile → find the one bottleneck → fix that → measure again**. This skill teaches that18loop and the highest-leverage fixes (pooling, batching, allocation control, asset budgets), and19points you at each engine's profiler. It pairs with `physics-tuning` for simulation cost.2021## When to use2223- Use when the frame rate is low or uneven, the game stutters/hitches, or it must hit a target24 (60 FPS desktop, 30/60 mobile) and currently doesn't.25- Use to decide *what* to optimize: profile, read the frame budget, and identify whether the CPU26 or GPU is the bottleneck before changing any code.27- Use to apply specific fixes: object pooling, draw-call/batch reduction, removing per-frame28 allocations and GC spikes, and setting asset budgets.2930**When *not* to use:** for physics jitter/tunneling/timestep specifically, use `physics-tuning`.31For the engine's concrete profiler UI and rendering settings, use that32engine skill (`godot-export` covers some build settings; engine cores cover the rest). This skill33is the cross-engine method and the shared fixes.3435## The golden rule: measure first, never guess3637Most performance "fixes" applied without profiling target the wrong thing and add complexity for38no gain. **Do not optimize code you have not measured.** Open the profiler, find the single39biggest cost in a representative scene on representative hardware, and fix that. Re-measure to40confirm the fix helped before moving on. Profile a **release/optimized build** where it matters —41editor and debug builds lie (editor overhead, no compiler optimization).4243## Core workflow44451. **Define the target and reproduce.** State the goal (e.g. 60 FPS = 16.67 ms/frame) and find a46 repeatable worst-case scene. "Sometimes slow" is unfixable; a reproducible spike is fixable.472. **Profile before touching code.** Run the engine profiler and read the frame: total frame48 time, and the split between CPU (game logic, physics, scripts) and GPU (rendering).493. **Find the bottleneck — CPU or GPU.** If GPU time ≫ CPU, attack draw calls/overdraw/shaders/50 resolution. If CPU time dominates, attack scripts/physics/allocations. Fixing the wrong side51 does nothing.524. **Fix the single biggest cost.** Prefer an **algorithmic** win (do less work, cache, spatial53 partition, run less often) over micro-optimizing a hot line. Apply the matching shared fix54 (pooling, batching, allocation removal).555. **Re-measure on the same scene/hardware.** Confirm the number moved. Keep or revert based on56 data, not intuition.576. **Set budgets so it stays fixed.** Per-frame ms budgets per subsystem, plus asset budgets58 (texture sizes, triangle counts, draw-call ceilings); add a perf check to verification.597. **Report measured numbers.** State before/after frame time, the bottleneck found, and the fix60 — never "should be faster". If you could only measure in-editor, say so.6162## Patterns6364### 1. Frame budget math (turn "feels slow" into a number)6566```text67target FPS → frame budget: 60 FPS = 16.67 ms | 30 FPS = 33.3 ms | 120 FPS = 8.33 ms68The WHOLE frame (CPU sim + render submit + GPU) must fit the budget; the GPU runs in parallel,69so the slower of CPU-frame and GPU-frame sets your FPS. Allocate sub-budgets, e.g. @60 FPS:70 gameplay/scripts ~5 ms · physics ~3 ms · rendering(CPU submit) ~4 ms · UI/other ~2 ms · slack.71If one subsystem blows its slice, that's your target — not whatever you assumed.72```7374### 2. Measure with the engine profiler (do this before any fix)7576```text77Godot 4.7 : Debugger ▸ Profiler (script/physics time), Visual Profiler (CPU vs GPU render time78 per pass) and Monitors tab (FPS, draw calls, memory).79 In code: Performance.get_monitor(Performance.TIME_PROCESS) returns SECONDS80 (× 1000 for ms); Performance.RENDER_TOTAL_DRAW_CALLS_IN_FRAME for draw calls.81Unity 6.3 LTS : Profiler window (CPU/GPU/Memory/Rendering modules) + Frame Debugger for draw calls.82 In code: ProfilerRecorder on "CPU Main Thread Frame Time" / "GPU Frame Time"83 (release players need Frame Timing Stats enabled in Player Settings).84Unreal 5.8 : `stat unit` (Frame / Game / Draw / RHIT / GPU ms), `stat fps`,85 `stat scenerendering` (draw calls); Unreal Insights for deep traces.86# Read the split: Game = gameplay thread, Draw = render thread (both CPU), GPU = the graphics card.87# Whichever is closest to Frame is the bottleneck; that decides the fix.88```8990### 3. Object pooling (stop allocating/freeing in hot loops)9192```gdscript93# Bullets, particles, enemies, damage numbers: reuse a fixed set instead of instantiate()/free()94# every frame — that thrashes memory and (in C#) feeds the GC.95var _pool: Array[Node2D] = [] # Node3D for 3D; both have `visible`96func acquire() -> Node2D:97 var n: Node2D = _pool.pop_back() if not _pool.is_empty() else bullet_scene.instantiate()98 n.set_process(true); n.visible = true99 return n100func release(n: Node2D) -> void:101 n.set_process(false); n.visible = false # disable + hide; DON'T free102 _pool.append(n) # back to the pool for reuse103# RIGHT: pre-warm the pool at load; reuse. WRONG: instantiate()/queue_free() per shot.104```105106### 4. Cut draw calls (the most common GPU-side win)107108```text109Draw calls and render-state changes (material/shader/texture/blend switches) cost CPU submit time;110thousands of them make the render thread the bottleneck. 2D batchers merge runs of sprites that111share state (most bind several textures per batch), so ordering and atlasing decide the count.112- Atlas textures and share materials so sprites/meshes batch into one call.113- Identical meshes → GPU instancing (Unity; under URP/HDRP the SRP Batcher or GPU Resident Drawer114 takes precedence), MultiMesh / MultiMeshInstance (Godot), Instanced Static Mesh (Unreal).115- Static geometry → static batching / baking; mark non-moving objects static.116- Reduce overdraw: limit large overlapping transparent/particle layers (they re-shade pixels).117- If fill rate dominates, lower render resolution: 2× pixel ratio means 4× the pixels of 1×.118 For three.js game defaults and warm-up-aware resolution tuning, read `threejs-scene-setup`.119- Fewer real-time lights/shadows; bake lighting where it doesn't move.120Measure draw calls before and after — the count should drop, and so should GPU frame time.121```122123### 5. Kill per-frame allocations (GC spikes = stutter)124125```csharp126// Unity 6.3 LTS (C#). Allocating every frame fills the managed heap; the GC then stalls a frame.127// WRONG (new array + scene walk every call):128// foreach (var e in FindObjectsByType<Enemy>(FindObjectsSortMode.None)) ... // + LINQ, new[]129// (FindObjectsOfType is obsolete in Unity 6.3; its replacement still allocates.)130// RIGHT: cache references once, reuse buffers, avoid LINQ/boxing in Update.131void Update() {132 _hits = Physics.RaycastNonAlloc(ray, _hitBuffer); // reuse a preallocated array133 for (int i = 0; i < _hits; i++) { /* ... */ } // no per-frame allocation134} // hit order is undefined and a full buffer may miss the nearest hit: size it, sort if needed135// Godot/GDScript: avoid building new arrays/dictionaries every frame in _process; reuse them.136```137138## Pitfalls139140- **Optimizing without profiling.** The intuitive culprit is usually wrong. Measure first, every141 time.142- **Profiling the editor / a debug build.** Editor overhead and unoptimized code mislead. Profile143 a release build on target hardware for real numbers.144- **Fixing the wrong side.** Micro-optimizing CPU code when the GPU is the bottleneck (or vice145 versa) changes nothing. Check the CPU-vs-GPU split first.146- **Micro-optimizing over algorithm.** Shaving a function when an O(n²) loop or a per-frame147 full-scene query is the real cost. Reduce the work, don't polish it.148- **Instantiate/free in hot loops.** Spawning and destroying bullets/particles every frame causes149 fragmentation and GC spikes. Pool them.150- **Per-frame allocations / LINQ / boxing in `Update`** (C#) feed the GC → periodic hitches.151 Cache and reuse.152- **Draw-call explosion** from unique materials and unbatched sprites/meshes. Atlas, share153 materials, instance, batch.154- **Unity "Enable GPU Instancing" with no effect** under URP/HDRP: the SRP Batcher takes155 precedence for compatible shaders. Check the Frame Debugger; for many identical meshes use the156 GPU Resident Drawer (Forward+, compute-capable APIs, not OpenGL ES).157- **Overdraw** from stacked transparents/particles/full-screen effects re-shading pixels.158- **No budgets.** Without per-subsystem ms and asset ceilings, performance silently regresses;159 enforce them in your build/CI checks.160- **Optimizing too early.** Don't contort a prototype for performance before it's fun or measured.161162## References163164- For per-engine profiler walkthroughs, the CPU-vs-GPU triage flowchart, a complete pooling165 manager, batching/instancing rules per engine, allocation/GC guidance, LOD/culling, and asset166 budgets (texture sizes, triangle counts, audio, mobile thermals), read167 `references/profiling-and-budgets.md`.168169## Related skills170171- `physics-tuning` — simulation cost, fixed-step budget, sleeping bodies, broadphase layers.172- `godot-export` — release/build settings that affect measured performance.173- `procedural-gen`, `game-ai` — common CPU hotspots (generation, pathfinding) to budget and defer.174- `roguelike`, `tower-defense`, `survival-crafting` — entity-heavy genres that need pooling/budgets.