Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Optimization and Publishing

Profiler and Optimization in Unity

Find and fix performance problems in Unity - the Profiler, frame budgets, garbage collection, draw calls, batching and the rules of optimization - with runnable allocation and timing stand-ins.

A game that runs at 25 frames per second on a mid-range phone is a game people uninstall. Optimization is the skill of finding what is slow and fixing exactly that. The golden rule: measure first. Guessing leads you to spend a week speeding up code that takes 0.1 ms.

This lesson covers frame budgets, the Unity Profiler and related tools, the three usual bottlenecks (CPU scripts, garbage collection, rendering), and concrete fixes. The Unity tools are described in text with read-only code; the runnable C# stand-ins demonstrate the ideas of budgets, allocations and caching.

The frame budget

A game at 60 fps has 16.67 ms per frame; at 30 fps, 33.3 ms; a VR headset at 90 fps only 11.1 ms. Everything (scripts, physics, animation, rendering) must fit inside, and mobile devices also throttle when hot. So think in milliseconds, not in "feels slow".

C# Stand-in: frame budget calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Here the total (18.5 ms) misses 60 fps, and the three largest items are where to look first. Always attack the biggest cost.

The Profiler

Open Window > Analysis > Profiler. Press Play and it records every frame. Key modules:

  • CPU Usage: a timeline and a Hierarchy view that lists every function with Total, Self and GC Alloc columns. Sort by Self ms to find hot code. Spikes in the timeline show one-off hitches (loading, garbage collection).
  • Rendering: batches, SetPass calls, triangles and vertices.
  • Memory: managed heap, textures, meshes; use the Memory Profiler package for snapshots and leak hunting.
  • Audio, Physics, UI modules for specific systems.

Profile a development build on the real device (Build Settings > Development Build + Autoconnect Profiler). The Editor has a lot of overhead and a PC is much faster than a phone. Use Profiler.BeginSample("MyWork") / EndSample() or ProfilerMarker to label your own code, and the Frame Debugger to step through draw calls.

C#
using Unity.Profiling;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    static readonly ProfilerMarker markerAI = new("Spawner.AI");

    void Update()
    {
        using (markerAI.Auto())
        {
            // expensive work now appears by name in the Profiler
        }
    }
}

Garbage collection and allocations

C# objects live on a managed heap. When you create garbage (short-lived allocations), the garbage collector (GC) eventually runs and can cause a visible frame spike. The fix is to allocate less in code that runs every frame:

  • Avoid new in Update: arrays, lists, strings, LINQ queries, closures and boxing allocate.
  • Cache GetComponent and Camera.main-style lookups in Awake.
  • Reuse collections: list.Clear() instead of a new list; Physics.OverlapSphereNonAlloc instead of OverlapSphere.
  • Build strings with StringBuilder or TMP's SetText; avoid "a" + b + "c" per frame.
  • Pool frequently created objects (see Object pooling and memory).

The stand-in measures managed allocations with GC.GetAllocatedBytesForCurrentThread() so you can see the difference between a wasteful and a cached version.

C# Stand-in: measuring allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

CPU: scripts and physics

  • Do less often. Not everything must run every frame: an AI can think every 0.2 s, a distance check every few frames.
  • Remove empty Update methods. Even empty ones cost a call across the native boundary.
  • Cache and compare cheaply: compare sqrMagnitude instead of Vector3.Distance (it avoids a square root) and CompareTag("X") instead of tag == "X".
  • Physics: simplify colliders (primitives over mesh colliders), use layers and the Layer Collision Matrix, raise the Fixed Timestep only if you must, and avoid moving static colliders.
  • Jobs and Burst: the C# Job System and Burst compiler run heavy math in parallel; reach for them only after profiling proves a loop is the bottleneck.
C# Stand-in: cache the lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Rendering: draw calls, batching and overdraw

Rendering costs usually dominate on mobile.

  • Draw calls and SetPass calls: each material/mesh change costs CPU time. Share materials, use SRP Batcher (URP), GPU Instancing for many copies, Static Batching for non-moving geometry and Sprite Atlases for 2D.
  • Overdraw: drawing many transparent layers on the same pixels; check the Scene view's Overdraw mode. Large particle effects and stacked UI panels are common culprits.
  • Resolution and fill rate: lower the render scale or use dynamic resolution on mobile. Bring shadows, MSAA and post-processing down.
  • Textures: use compressed formats (ASTC for mobile, BC7 on desktop), power-of-two sizes where required, and mipmaps for 3D. Check the Max Size import setting.
  • Culling: LOD groups, occlusion culling and a short camera far-clip plane.
  • UI: split Canvases so a changing health number does not rebuild the entire static menu, and disable Raycast Target on decoration.

A repeatable workflow

  1. Define a target (for example 60 fps on a specific phone).
  2. Profile on the device; find the biggest cost; check whether it is CPU or GPU bound.
  3. Change one thing; measure again.
  4. Keep the change only if it helped; repeat.

Do not optimize code that is not hot, and do not make code unreadable to save microseconds you cannot measure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many milliseconds does one frame have at 60 fps?

    1000 ms divided by 60 frames is about 16.67 ms.
  2. 2. Where should you profile for the most trustworthy numbers?

    The Editor adds overhead and a PC is much faster than a typical phone.
  3. 3. Which is a common source of per-frame garbage?

    They allocate on the managed heap and eventually trigger the garbage collector.
  4. 4. What does the SRP Batcher help with?

    It batches material property uploads so many objects with the same shader render cheaply.

Summary

  • Measure first: frame budget in ms, Profiler on a real device, one change at a time.
  • Reduce allocations in hot paths, cache lookups, and do work less often.
  • Rendering wins: batching, atlases, compressed textures, fewer transparent layers, LODs.
  • Use Jobs and Burst only when the profile says a loop is the problem.

Next: Object Pooling and Memory