←All patterns
Optimization

Dirty Flag

Remember that derived data is out of date and recompute it only when someone actually needs it.

What Is It?

Some values are expensive to derive from others: a world-space position built by walking up a hierarchy, a navmesh path, a combined mesh, a sorted leaderboard. The Dirty Flag pattern keeps a cached result plus a single bool isDirty that says "the inputs changed since I last computed this".

Writes are cheap: changing a local position just sets the flag (and, in a hierarchy, flags every descendant). Reads are lazy: the getter checks the flag, recomputes only if dirty, clears the flag and returns the cache. Ten writes in a frame cost one recompute instead of ten.

Unity itself does this inside Transform — moving a parent does not immediately recompute every child's localToWorldMatrix; it is marked and resolved when queried or rendered. Transform.hasChanged is the public face of the same idea.

When Is It Used?

Use it when a derived value is costly to compute, its inputs change in bursts, and it is read less often than it is written — or read many times between changes.

Classic fits are custom scene graphs, procedural mesh rebuilding, UI layout, pathfinding caches and stat systems where buffs stack into a final number.

Skip it when the computation is trivial (adding two numbers) or the value changes on every single read anyway; the flag bookkeeping then costs more than it saves.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Dirty Flag Pattern
frames0recalcs0naive would0saved0%
world (cached)
ShipTurretBarrelWingEngine
tap a node to select it
Console
Press a button to see what happens…

Code

Assets / Scripts / Optimization/ DirtyFlag ›DirtyFlagTester.cs
using UnityEngine;

namespace Patterns.Optimization.DirtyFlag
{
    /// <summary>
    /// Builds a Ship → Turret → Barrel hierarchy, wiggles it and reports how
    /// many world positions were actually recomputed.
    /// </summary>
    public class DirtyFlagTester : MonoBehaviour
    {
        [SerializeField] private float wiggleSpeed = 2f;

        private SceneGraph graph;
        private SceneNode ship, turret, barrel;

        private void Awake()
        {
            graph = new SceneGraph();
            ship = graph.Create("Ship", null, Vector3.zero);
            turret = graph.Create("Turret", ship, new Vector3(0f, 1f, 0f));
            barrel = graph.Create("Barrel", turret, new Vector3(0f, 0f, 1.5f));
        }

        private void Update()
        {
            // Only the turret moves this frame; the ship stays clean.
            turret.LocalPosition = new Vector3(Mathf.Sin(Time.time * wiggleSpeed), 1f, 0f);

            // Reading the barrel recomputes Turret + Barrel, not Ship.
            Vector3 muzzle = barrel.WorldPosition;
            Debug.DrawRay(muzzle, Vector3.forward, Color.yellow);
        }

        private void LateUpdate()
        {
            if (Time.frameCount % 120 == 0)
                Debug.Log($"Recomputes so far: {SceneNode.RecomputeCount}");
        }
    }
}
3 files · namespace Patterns.Optimization.DirtyFlagC# · UTF-8 · LF

Before & After

Real-world smell: a world position recomputed on every read. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

SceneNode.WorldPosition walks the whole parent chain every time it is read: the barrel asks the turret, the turret asks the ship, and so on up to the root.

The renderer, the aiming code and the physics checks all read the same positions every frame, so a deep hierarchy pays for the full walk again and again even when nothing moved. On a completely still scene, RecomputeCount still climbs every frame.

✓ What changed

  • Each node now keeps cachedWorld and an isDirty flag, plus a list of its children.
  • The LocalPosition setter ignores writes that change nothing and calls SetDirty(), which marks the node and its whole subtree.
  • The WorldPosition getter recomputes only while isDirty is set and then clears it; clean reads just return the cache.
  • SetDirty returns early at a node that is already dirty, so ten moves in one frame still cost one recompute per node.
SceneNode.Before.cs → SceneNode.After.cs+24/−5
1+using System.Collections.Generic;
12 using UnityEngine;
23
34 namespace Patterns.Optimization.DirtyFlag
45 {
56 /// <summary>
6− /// Without a dirty flag: every read of the world position walks up the
7− /// whole parent chain again, even when nothing has moved.
7+ /// With a dirty flag: writes mark the node (and its subtree) dirty;
8+ /// reads recompute lazily, and only when something actually changed.
89 /// </summary>
910 public class SceneNode
1011 {
1112 public static int RecomputeCount { get; private set; }
1213
14+ private readonly List<SceneNode> children = new();
1315 private Vector3 localPosition;
16+ private Vector3 cachedWorld;
17+ private bool isDirty = true;
1418
1519 public string Name { get; }
1620 public SceneNode Parent { get; }
1721
1822 public SceneNode(string name, SceneNode parent, Vector3 local)
1923 {
2024 Name = name;
2125 Parent = parent;
2226 localPosition = local;
27+ parent?.children.Add(this);
2328 }
2429
2530 public Vector3 LocalPosition
2631 {
2732 get => localPosition;
2833 set
2934 {
35+ if (localPosition == value) return;
3036 localPosition = value;
37+ SetDirty();
3138 }
3239 }
3340
3441 public Vector3 WorldPosition
3542 {
3643 get
3744 {
38− // Always correct, always recomputed: N reads cost N walks.
39− RecomputeCount++;
40− return Parent == null ? localPosition : Parent.WorldPosition + localPosition;
45+ if (isDirty)
46+ {
47+ cachedWorld = Parent == null ? localPosition : Parent.WorldPosition + localPosition;
48+ isDirty = false;
49+ RecomputeCount++;
50+ }
51+ return cachedWorld;
4152 }
4253 }
54+
55+ private void SetDirty()
56+ {
57+ if (isDirty) return; // subtree is already marked
58+ isDirty = true;
59+ foreach (var child in children)
60+ child.SetDirty();
61+ }
4362 }
4463 }

Advantages & Disadvantages

+ Advantages

  • Avoids redundant work: many writes collapse into one recompute.
  • Lazy evaluation means values nobody reads are never computed at all.
  • Simple to retrofit — a bool and a getter around existing code.

− Disadvantages

  • Forgetting to set the flag on one write path gives you stale data that is very hard to spot.
  • Recompute cost moves to the first read, which can cause an unexpected spike at a bad moment.
  • Hierarchies need careful propagation so children are marked whenever an ancestor changes.

Tips

  1. 01Funnel every write through a setter that calls SetDirty(); make the backing field private so nothing can bypass it.
  2. 02When propagating to children, stop early if a node is already dirty — its subtree must already be marked.
  3. 03If a spike on first read is a problem, resolve dirty values at a predictable point such as LateUpdate instead of inside the getter.
  4. 04Use Transform.hasChanged (and reset it yourself) to skip work in scripts that only care when an object actually moved.
  5. 05Expose a debug counter of recomputes while profiling; it makes the savings — or a missing SetDirty — obvious.