What Is It?
A CPU does not read memory one value at a time. It fetches a whole cache line, usually 64 bytes, and reading from cache is many times faster than going out to RAM. If the next value your loop needs is already in that line, it is almost free; if it is somewhere else, the CPU stalls on a cache miss.
A List<ParticleObject> of classes is a list of pointers. Each particle lives wherever the allocator put it, often far from the previous one, so every iteration can be a miss. A ParticleHot[] of structs puts the particles back to back: one fetch brings in the next one or two, and the hardware prefetcher sees the pattern and loads ahead.
Hot/cold splitting goes one step further. The update loop only touches position, velocity and life; the emitter name, spawn time and debug colour are needed rarely. Moving those cold fields into a parallel array means every byte the loop pulls into the cache is a byte it actually uses.
When Is It Used?
Use it for loops that touch thousands of similar items every frame: particles, projectiles, boids, crowd agents, simple physics, damage-over-time ticks.
It is the core idea behind Unity DOTS. ECS stores components in tightly packed chunks, NativeArray<T> gives you unmanaged contiguous memory, Jobs spreads the loop across cores and Burst compiles it to SIMD.
Do not reorganise code for a loop over 30 objects. Profile first; if the hot path is not memory-bound, the clearer object-oriented version is the better choice.
Interactive Demo
Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.
Code
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
namespace Patterns.Optimization.DataLocality
{
/// <summary>
/// Owns the particles as two parallel NativeArrays (hot and cold) and
/// schedules the Burst job over the hot one every frame.
/// </summary>
public class ParticleSimulation : MonoBehaviour
{
[SerializeField] private int capacity = 100_000;
private NativeArray<ParticleHot> hot;
private NativeArray<ParticleCold> cold;
private JobHandle handle;
private void OnEnable()
{
hot = new NativeArray<ParticleHot>(capacity, Allocator.Persistent);
cold = new NativeArray<ParticleCold>(capacity, Allocator.Persistent);
for (int i = 0; i < capacity; i++)
{
hot[i] = new ParticleHot { Life = 5f, Drag = 0.1f, Velocity = new float3(0f, 5f, 0f) };
cold[i] = new ParticleCold { EmitterId = 0, SpawnTime = Time.time };
}
}
private void Update()
{
var job = new UpdateParticlesJob
{
Particles = hot,
Gravity = new float3(0f, -9.81f, 0f),
DeltaTime = Time.deltaTime,
};
handle = job.Schedule(hot.Length, 1024);
}
// Rendering reads positions only after the job has finished.
private void LateUpdate() => handle.Complete();
private void OnDisable()
{
handle.Complete();
hot.Dispose();
cold.Dispose();
}
}
}using Unity.Mathematics;
namespace Patterns.Optimization.DataLocality
{
/// <summary>
/// Hot data: read and written every frame for every particle.
/// 32 bytes, so exactly two particles fit in one 64-byte cache line.
/// </summary>
public struct ParticleHot
{
public float3 Position; // 12 bytes
public float Life; // 4 bytes
public float3 Velocity; // 12 bytes
public float Drag; // 4 bytes
}
/// <summary>
/// Cold data: touched only on spawn, on death or by debug tools.
/// Kept in a separate array at the same index, so it never takes up
/// space in the cache lines the update loop streams through.
/// </summary>
public struct ParticleCold
{
public int EmitterId;
public float SpawnTime;
public uint DebugColor;
public int SpriteIndex;
}
}using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
namespace Patterns.Optimization.DataLocality
{
/// <summary>
/// The hot loop. It walks a NativeArray front to back, so the hardware
/// prefetcher keeps the next cache lines ready, and Burst turns the
/// math into SIMD instructions.
/// </summary>
[BurstCompile]
public struct UpdateParticlesJob : IJobParallelFor
{
public NativeArray<ParticleHot> Particles;
public float3 Gravity;
public float DeltaTime;
public void Execute(int i)
{
ParticleHot p = Particles[i]; // one contiguous 32-byte read
p.Velocity += Gravity * DeltaTime;
p.Velocity *= 1f - p.Drag * DeltaTime;
p.Position += p.Velocity * DeltaTime;
p.Life -= DeltaTime;
Particles[i] = p; // one contiguous 32-byte write
}
}
}Before & After
Real-world smell: a particle list of classes mixing hot and cold fields. Here is the code without the pattern, the refactored version, and the exact diff between them.
! What’s wrong with it?
ParticleManager keeps a List<ParticleObject>, and ParticleObject is a class with position, velocity and life next to EmitterName, SpawnTime, DebugColor and a Sprite. The update loop is a clean foreach that looks perfectly reasonable.
Each element is a separate heap object, so walking the list jumps around memory and stalls on cache misses. Each object is also padded with cold fields the loop never reads, which wastes most of every cache line it does load. At 10,000 particles the loop shows up in the Profiler even though the math is trivial.
✓ What changed
- The
List<ParticleObject>of classes becomes two parallel struct arrays,ParticleHotData[]andParticleColdData[]. - The loop iterates
hotwith aforindex and areflocal, so it streams through contiguous memory and writes in place. - Cold fields such as
EmitterNameandSpritemove toParticleColdData, so they no longer travel through the cache every frame. - Struct arrays are allocated once in
Awake; adding particles no longer creates garbage.
using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Optimization.DataLocality
{
/// <summary>
/// Without data locality: a list of class instances, each a separate heap
/// object that mixes per-frame fields with rarely used ones.
/// </summary>
public class ParticleManager : MonoBehaviour
{
private readonly List<ParticleObject> particles = new List<ParticleObject>();
private void Update()
{
float dt = Time.deltaTime;
Vector3 gravity = Physics.gravity;
// Each element is a pointer; each dereference can be a cache miss.
foreach (ParticleObject p in particles)
{
p.Velocity += gravity * dt;
p.Position += p.Velocity * dt;
p.Life -= dt;
}
}
}
public class ParticleObject
{
public Vector3 Position; // hot
public Vector3 Velocity; // hot
public float Life; // hot
public string EmitterName; // cold
public float SpawnTime; // cold
public Color DebugColor; // cold
public Sprite Sprite; // cold
}
}using UnityEngine;
namespace Patterns.Optimization.DataLocality
{
/// <summary>
/// With data locality: hot fields packed into one struct array that the
/// loop streams through; cold fields in a parallel array at the same index.
/// </summary>
public class ParticleManager : MonoBehaviour
{
[SerializeField] private int capacity = 10_000;
private ParticleHotData[] hot;
private ParticleColdData[] cold;
private int count;
private void Awake()
{
hot = new ParticleHotData[capacity];
cold = new ParticleColdData[capacity];
}
private void Update()
{
float dt = Time.deltaTime;
Vector3 gravity = Physics.gravity;
// Contiguous structs: the next particle is already in the cache line.
for (int i = 0; i < count; i++)
{
ref ParticleHotData p = ref hot[i];
p.Velocity += gravity * dt;
p.Position += p.Velocity * dt;
p.Life -= dt;
}
}
}
public struct ParticleHotData
{
public Vector3 Position; // hot
public Vector3 Velocity; // hot
public float Life; // hot
}
public struct ParticleColdData
{
public string EmitterName; // cold
public float SpawnTime; // cold
public Color DebugColor; // cold
public Sprite Sprite; // cold
}
}Advantages & Disadvantages
+ Advantages
- Large loops can run several times faster with the same algorithm, just from fewer cache misses.
- Struct arrays create no garbage per element, so the GC has nothing to scan or collect.
- The same layout is what Jobs, Burst and SIMD need, so it is the first step towards DOTS.
− Disadvantages
- Code becomes less object-oriented: an item is an index into several arrays rather than one object with methods.
- Adding, removing and reordering items needs care (swap-back removal, keeping parallel arrays in sync).
- The benefit is invisible until the data set is large; for small counts it is complexity without payoff.
Tips
- 01Use structs in arrays or
NativeArray<T>, and iterate with a plainforfrom0tocount. Usereflocals to modify elements in place. - 02Split fields by how often the hot loop touches them. If a field is read once per second, it does not belong next to position and velocity.
- 03Remove items by swapping the last element into the hole, so the array stays dense and the loop never skips gaps.
- 04Move the loop into an
IJobParallelForwith[BurstCompile]once the data is contiguous; Burst can only vectorise what it can stream. - 05Measure with the Profiler before and after. A cache-friendly layout that does not show up in the timings was not your bottleneck.