Jobs & Burst
Most Unity game code runs on the main thread, while modern CPUs have 6 to 16 cores sitting mostly idle. The C# Job System lets you run work on worker threads safely, and the Burst compiler (com.unity.burst) compiles those jobs into fast native code with SIMD. You can use both without ECS, from ordinary MonoBehaviours.
A parallel job
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
[BurstCompile]
struct BoidStepJob : IJobParallelFor
{
[ReadOnly] public NativeArray<float3> Velocities;
public NativeArray<float3> Positions;
public float DeltaTime;
public void Execute(int i) // called once per index, on any worker thread
{
Positions[i] += Velocities[i] * DeltaTime;
}
}
public class Swarm : MonoBehaviour
{
const int Count = 20000;
NativeArray<float3> positions, velocities;
JobHandle handle;
void OnEnable()
{
positions = new NativeArray<float3>(Count, Allocator.Persistent);
velocities = new NativeArray<float3>(Count, Allocator.Persistent);
for (int i = 0; i < Count; i++) velocities[i] = new float3(0f, 1f, 0f);
}
void Update()
{
var job = new BoidStepJob { Positions = positions, Velocities = velocities, DeltaTime = Time.deltaTime };
handle = job.Schedule(Count, 64); // batches of 64 indices per work item
}
void LateUpdate()
{
handle.Complete(); // wait (usually already finished) before reading results
// copy positions to renderers, e.g. via Graphics.RenderMeshInstanced
}
void OnDisable()
{
handle.Complete();
positions.Dispose(); // native memory is not garbage collected
velocities.Dispose();
}
}Key rules:
- Jobs are structs and can only use blittable data and native containers (
NativeArray,NativeList,NativeHashMap…), never managed objects,GameObjects or most of the Unity API. - Native containers must be disposed.
Allocator.Temp(this frame, not in jobs),TempJob(up to four frames),Persistent(until you dispose). Leaks are reported in the Console. - The safety system catches races in the editor: two jobs writing the same array without a dependency throw an exception that names both jobs. Pass dependencies:
var h2 = job2.Schedule(h1);. [ReadOnly]lets several jobs read the same container at once.- Schedule early, complete late: schedule in
Update, complete inLateUpdateor the next frame, and do other work in between.
Burst
[BurstCompile] on the job struct is all it takes. Burst compiles High-Performance C# (no managed allocations, no exceptions in release, structs and native containers) into LLVM-optimized machine code, using Unity.Mathematics types (float3, math.dot) that map to SIMD instructions. Gains of 10× or more over plain C# are common for math-heavy loops. Open Jobs > Burst > Open Inspector to see the generated assembly.
A model: batches and dependencies
Schedule(count, batchSize) splits the index range into batches that idle workers grab. Dependencies form a chain: a job doesn't start before the jobs it depends on finish. The model runs the batches deterministically (on one thread) but prints the plan a scheduler would execute, and checks that the result equals a plain loop:
using System;
using System.Collections.Generic;
const int Count = 10, BatchSize = 4, Workers = 2;
var positions = new float[Count];
var velocities = new float[Count];
for (int i = 0; i < Count; i++) velocities[i] = i;
// Job A: integrate positions. Job B (depends on A): clamp to a ceiling.
var scheduler = new Scheduler(Workers);
int a = scheduler.ScheduleParallel("Integrate", Count, BatchSize, i => positions[i] += velocities[i] * 0.5f);
int b = scheduler.ScheduleParallel("Clamp", Count, BatchSize, i => positions[i] = Math.Min(positions[i], 3f), dependsOn: a);
scheduler.CompleteAll();
Console.WriteLine("result: " + string.Join(" ", positions));
var check = new float[Count];
for (int i = 0; i < Count; i++) check[i] = Math.Min(velocities[i] * 0.5f, 3f);
Console.WriteLine(quot;matches single-threaded loop: {check.AsSpan().SequenceEqual(positions)}");
class Scheduler
{
readonly int workers;
readonly List<(string Name, int Start, int End, Action<int> Body, int Job)> batches = new();
readonly List<int> deps = new();
public Scheduler(int w) => workers = w;
public int ScheduleParallel(string name, int count, int batchSize, Action<int> body, int dependsOn = -1)
{
int job = deps.Count;
deps.Add(dependsOn);
for (int s = 0; s < count; s += batchSize)
batches.Add((name, s, Math.Min(s + batchSize, count), body, job));
return job;
}
public void CompleteAll()
{
int round = 0;
var done = new HashSet<int>();
var pending = new List<(string Name, int Start, int End, Action<int> Body, int Job)>(batches);
while (pending.Count > 0)
{
// each round, every worker takes one ready batch whose dependency job has fully finished
var ready = pending.FindAll(x => deps[x.Job] < 0 || done.Contains(deps[x.Job]));
var taken = ready.GetRange(0, Math.Min(workers, ready.Count));
round++;
for (int w = 0; w < taken.Count; w++)
{
var t = taken[w];
for (int i = t.Start; i < t.End; i++) t.Body(i);
Console.WriteLine(quot;round {round}: worker {w} runs {t.Name}[{t.Start}..{t.End - 1}]");
pending.Remove(t);
}
for (int j = 0; j < deps.Count; j++)
if (!pending.Exists(x => x.Job == j)) done.Add(j);
}
}
}round 1: worker 0 runs Integrate[0..3]
round 1: worker 1 runs Integrate[4..7]
round 2: worker 0 runs Integrate[8..9]
round 3: worker 0 runs Clamp[0..3]
round 3: worker 1 runs Clamp[4..7]
round 4: worker 0 runs Clamp[8..9]
result: 0 0.5 1 1.5 2 2.5 3 3 3 3
matches single-threaded loop: True
Round 2 leaves a worker idle: Clamp can't start until every batch of Integrate is done. Smaller batches balance load better but add scheduling overhead; 32 to 128 is a typical range for cheap per-element work. Use the Profiler's Timeline view to see real jobs on worker threads.
When to reach for Jobs + Burst
- Hot loops over many elements: flocking, custom particle simulations, procedural mesh or terrain generation, pathfinding grids, raycast batches (
RaycastCommand.ScheduleBatch). - Not for code that's mostly Unity API calls or a few dozen objects: the copying into native containers costs more than it saves.
Test yourself
Which data can a Burst-compiled job use?
- Any C# class
- Blittable structs and native containers such as NativeArray
- GameObjects and Transforms
- Strings and Lists
Two jobs write to the same NativeArray and the second doesn't depend on the first. What happens in the editor?
- Undefined results, silently
- The safety system throws an exception naming the conflicting jobs
- Unity merges the writes
- The second job is skipped
Why must a NativeArray with Allocator.Persistent be disposed?
- It's a managed object
- It is unmanaged memory the GC doesn't free
- Burst requires it every frame
- It doesn't need to be