←All patterns
Optimization

Data Locality

Lay data out in memory in the order your loop reads it, so the CPU cache can stream it instead of waiting on RAM.

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.

Data Locality Pattern
misses0hits0bytes loaded0useful0%
RAM · one row = one 64-byte cache linehotcoldpointerheader
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
CPU cache
empty
6 lines max
List<ParticleObject>~1377 ns · 15 misses
Particle[] (hot+cold)~223 ns · 1 misses
Hot[] + Cold[]~159 ns · 1 misses
Estimate for 16 particles: miss ≈ 80 ns, prefetched line ≈ 8 ns, hit ≈ 1 ns
Console
Press a button to see what happens…

Code

Assets / Scripts / Optimization/ DataLocality ›ParticleSimulation.cs
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();
        }
    }
}
3 files · namespace Patterns.Optimization.DataLocalityC# · UTF-8 · LF

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[] and ParticleColdData[].
  • The loop iterates hot with a for index and a ref local, so it streams through contiguous memory and writes in place.
  • Cold fields such as EmitterName and Sprite move to ParticleColdData, so they no longer travel through the cache every frame.
  • Struct arrays are allocated once in Awake; adding particles no longer creates garbage.
ParticleManager.Before.cs → ParticleManager.After.cs+21/−7
1−using System.Collections.Generic;
21 using UnityEngine;
32
43 namespace Patterns.Optimization.DataLocality
54 {
65 /// <summary>
7− /// Without data locality: a list of class instances, each a separate heap
8− /// object that mixes per-frame fields with rarely used ones.
6+ /// With data locality: hot fields packed into one struct array that the
7+ /// loop streams through; cold fields in a parallel array at the same index.
98 /// </summary>
109 public class ParticleManager : MonoBehaviour
1110 {
12− private readonly List<ParticleObject> particles = new List<ParticleObject>();
11+ [SerializeField] private int capacity = 10_000;
1312
13+ private ParticleHotData[] hot;
14+ private ParticleColdData[] cold;
15+ private int count;
16+
17+ private void Awake()
18+ {
19+ hot = new ParticleHotData[capacity];
20+ cold = new ParticleColdData[capacity];
21+ }
22+
1423 private void Update()
1524 {
1625 float dt = Time.deltaTime;
1726 Vector3 gravity = Physics.gravity;
1827
19− // Each element is a pointer; each dereference can be a cache miss.
20− foreach (ParticleObject p in particles)
28+ // Contiguous structs: the next particle is already in the cache line.
29+ for (int i = 0; i < count; i++)
2130 {
31+ ref ParticleHotData p = ref hot[i];
2232 p.Velocity += gravity * dt;
2333 p.Position += p.Velocity * dt;
2434 p.Life -= dt;
2535 }
2636 }
2737 }
2838
29− public class ParticleObject
39+ public struct ParticleHotData
3040 {
3141 public Vector3 Position; // hot
3242 public Vector3 Velocity; // hot
3343 public float Life; // hot
44+ }
45+
46+ public struct ParticleColdData
47+ {
3448 public string EmitterName; // cold
3549 public float SpawnTime; // cold
3650 public Color DebugColor; // cold
3751 public Sprite Sprite; // cold
3852 }
3953 }

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

  1. 01Use structs in arrays or NativeArray<T>, and iterate with a plain for from 0 to count. Use ref locals to modify elements in place.
  2. 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.
  3. 03Remove items by swapping the last element into the hole, so the array stays dense and the loop never skips gaps.
  4. 04Move the loop into an IJobParallelFor with [BurstCompile] once the data is contiguous; Burst can only vectorise what it can stream.
  5. 05Measure with the Profiler before and after. A cache-friendly layout that does not show up in the timings was not your bottleneck.