liveBook · Manning

Array of structs

As explained in High Performance Unity Game Development

An array whose elements are struct values stored together in the array's contiguous memory block.

An array of structs stores struct values together in the array’s contiguous memory block. Unlike an array of class references, its elements’ data is stored together, making its placement easier to plan for CPU cache access. section 2.5

In data-oriented design, separate arrays are usually preferred to maximize data locality. Group fields in an array of structs when they are always used together and no other logic needs them separately. section 2.5

Coin pickup animations

A coin flying from the pickup location to the UI needs a current position, target position, and velocity. Keeping those fields together in a CoinStruct array suits a system that processes them together. A string field would weaken locality because each string’s data is allocated separately. section 2.5

Listing 2.20 Example of struct and class arrays
public struct CoinStruct
{
    public Vector2 CurrentPosition;
    public Vector2 TargetPosition;
    public float Velocity;
}
 
public class CoinClass
{
    public Vector2 CurrentPosition;
    public Vector2 TargetPosition;
    public float Velocity;
}
 
CoinStruct CoinStructArray = new CoinStruct[4];
CoinClass CoinClassArray = new CoinClass[4];

The C# listing defines matching coin data as a struct and class, then declares an array of each for comparison. section 2.5

How High Performance Unity Game Development covers it

How deep it goes
Explains contiguous array storage and contrasts it with class-reference arrays, but does not provide performance measurements.
Examples
Uses coin pickup UI animations with current and target positions and velocity.
What it assumes
Builds on arrays and data locality, and compares C# structs with classes.
What you can do after
Evaluate whether related fields belong together in an array of structs or separate arrays.
How it connects
Connects to data-oriented design, data locality, cache misses, and arrays of classes.

Also explained in

Compare how 2 books explain array of structs →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.