--- name: data-oriented-design description: Organize code by data layout for performance — SoA vs AoS, ECS patterns, cache-friendly access. Use when object-oriented design causes cache misses or when restructuring performance-critical code. license: MIT --- ## The Core Principle Code transforms data. Always. Nothing else happens. The faster you accept this, the faster your code improves. Data-oriented design (DOD) asks: "How is the data actually laid out and processed?" rather than "What is this thing?" ## Mike Acton's Key Insight > "The single most important thing is to understand the data. What is the data? > What does it look like? How does it flow? How do we transform it? And then how > do we lay it out in memory to best facilitate that transformation?" Stop thinking about "objects" and "classes". Start thinking about: - What data do I have? - How does it flow through the system? - How is it laid out in memory? - How can I transform it most efficiently? --- ## The DOD Mindset ### Wrong Questions - "What is this?" - "What class should this be?" - "What does this object do?" - "How do I model this?" ### Right Questions - "What data do I have?" - "How does it flow?" - "How do I transform it?" - "How is it laid out?" - "What operations do I need to support?" --- ## Data Design First ### Start with Atomic Facts Identify the smallest, immutable truths about your domain: ``` NOT: "Player has a position, velocity, health, inventory..." BUT: "Position: [x, y, z], Velocity: [vx, vy, vz], Health: f32, Inventory: [item_id, ...]" ``` ### Use IDs to Tie Facts Together Don't embed related data. Reference it: ```rust // Bad: Embedded (duplication, cache pollution) struct Player { position: Vector3, velocity: Vector3, health: f32, inventory: Vec, weapon: Weapon, } // Good: Referenced (separation of concerns, cache-friendly) struct Player { id: EntityId, position_idx: u32, // Index into positions array velocity_idx: u32, // Index into velocities array stats_idx: u32, // Index into stats array } struct PositionComponent { x: f32, y: f32, z: f32 } // Contiguous array struct VelocityComponent { x: f32, y: f32, z: f32 } // Contiguous array struct StatsComponent { health: f32, mana: f32 } // Contiguous array ``` ### Build the Data Flow Graph ``` Input Data → Transform → Derived Data → Transform → Output ↓ [What we have] → [What we need] → [How to get there] ``` --- ## Memory Layout Matters ### The Hardware Reality ``` L1 Cache: ~32 KB, ~1 ns access L2 Cache: ~256 KB, ~4 ns access L3 Cache: ~8 MB, ~15 ns access RAM: ~GB, ~100 ns access CPU fetches 64 bytes at a time from RAM. ``` ### Arrays of Structures (AoS) vs Structure of Arrays (SoA) ```rust // Bad: Array of Structures (AoS) // To update all positions, you jump around memory struct Particle { position: Vector3, velocity: Vector3, color: Color, life: f32, } let particles: Vec = vec![]; // Good: Structure of Arrays (SoA) // Contiguous memory, cache-friendly iteration struct ParticleSystem { positions: Vec, velocities: Vec, colors: Vec, lives: Vec, } // Even better for SIMD: Interleaved hot data struct Particle { position: Vector3, // Hot: accessed every frame velocity: Vector3, // Hot: accessed every frame } let hot_particles: Vec = vec![]; // Cold data in separate structure ``` ### Why This Matters Updating 10,000 particles: - **AoS**: ~10,000 cache misses (jumping between structs) - **SoA**: ~10-100 cache misses (sequential access) That's 100-1000x difference in practice. --- ## Transform-Centric Design ### The Question For any operation, ask: 1. What data comes in? 2. What data goes out? 3. How do we transform? Don't ask "What is this thing?" Ask "What transformation do we need?" ### Example: Game Entity Processing ```rust // Object-oriented thinking: // "Entity has position, updates position, checks bounds, renders..." // Data-oriented thinking: // "We have [TransformData], we need [TransformedData]" // "Apply: position += velocity * dt" // "Then: clamp to bounds" // "Then: copy to render buffer" fn update_positions(positions: &mut [Vector3], velocities: &[Vector3], dt: f32) { for i in 0..positions.len() { positions[i] = positions[i] + velocities[i] * dt; } } ``` ### Batch Operations ```rust // Bad: Per-entity work fn process_entities(entities: &mut [Entity]) { for entity in entities.iter_mut() { entity.update(); entity.render(); entity.sync_network(); } } // Good: Bulk transformations fn transform_entities(entities: &mut [Entity], dt: f32) { // All physics for e in entities.iter_mut() { e.position += e.velocity * dt; } } fn render_entities(entities: &[Entity], renderer: &mut Renderer) { // All rendering (cache-friendly batch) for e in entities.iter() { renderer.submit(&e.position, &e.rotation, &e.mesh); } } fn network_sync(entities: &[Entity], buffer: &mut NetworkBuffer) { // All network serialization for e in entities.iter() { buffer.write(e.id, e.position); } } ``` --- ## Common DOD Patterns ### Component-Entity-System (ECS) Data and behavior separated: ```rust // Components = raw data arrays struct TransformStorage { positions: Vec, rotations: Vec, } struct VelocityStorage { velocities: Vec, } // Systems = transformations fn physics_system(transforms: &mut TransformStorage, velocities: &VelocityStorage, dt: f32) { for i in 0..transforms.positions.len() { transforms.positions[i] += velocities.velocities[i] * dt; } } ``` ### Hot/Cold Separation Separate frequently-accessed from rarely-accessed data: ```rust // Hot: Every frame struct HotData { position: Vector3, velocity: Vector3, } // Cold: Occasionally struct ColdData { name: String, achievements: Vec, chat_logs: Vec, } // Keep hot data contiguous, cold data can be heavier ``` ### Indirection Tables ```rust // Dense to sparse mapping for cache efficiency struct DenseToSparse { dense_count: u32, mapping: Vec, // dense_index -> sparse_key } // Only iterate active entities for dense_idx in 0..entity_count { let sparse_key = mapping[dense_idx]; process(sparse_key); } ``` --- ## Common Object-Oriented Traps ### Trap 1: Mirroring Mental Models ```rust // Bad: Thinking in categories class Player extends Entity class Enemy extends Entity class NPC extends Entity // Good: Thinking in data struct Position { x, y, z } struct Health { current, max } struct AIState { type, timer, target } // Query: all entities with Position + Health > 0 + AIState ``` ### Trap 2: Forcing Hierarchies Not everything is a tree: ```rust // Bad: Forced inheritance class GameObject class MobileObject extends GameObject class Character extends MobileObject // Good: Flat data + queries struct Transform { ... } struct Physics { ... } struct CharacterData { ... } // Query for each operation, not each type ``` ### Trap 3: Over-Generalizing ```rust // Bad: Abstract "component system" for everything abstract class Component class PositionComponent extends Component class VelocityComponent extends Component // Good: Solve the actual problem struct Position { x, y, z } struct Velocity { x, y, z } ``` --- ## When to Apply DOD ### Good Candidates - Processing large datasets (1000+ items) - Hot paths (called every frame, every request) - Tight loops with simple transformations - Games, simulations, data pipelines - Performance-critical code ### Less Critical - UI code (few elements, human-speed interaction) - One-off operations (init, config load) - Code that will never be in the hot path --- ## Refactoring for DOD ### Step 1: Identify Data What data flows through this code? ``` Input: [UserId, Action, Timestamp] Processing: [validate, apply, persist] Output: [Result, new state] ``` ### Step 2: Find the Hot Path What operations run most often? - Per-item in a loop? - Per-frame in a game? - Per-request in a server? ### Step 3: Layout Transformation ``` Current layout → Target layout AoS → SoA for iteration Hot/Cold split Add indirection if needed ``` ### Step 4: Transform in Bulk Replace per-item work with batch operations. --- ## Key Takeaways 1. **Data, not objects**: Think about memory layout first 2. **Transform, don't method**: Functions transform data, objects don't "do" things 3. **Batch by access pattern**: Group data by how it's accessed, not by what it "is" 4. **Measure**: Profile before and after. DOD only matters if it helps. 5. **Hot/Cold**: Separate frequently-accessed from rarely-accessed data 6. **Contiguous is king**: Sequential memory access is 100x faster than random --- ## Related Skills - `performance-optimization` - Profiling and optimization techniques - `refactoring-patterns` - General refactoring approaches