liveBook · Manning

Array of classes

As explained in High Performance Unity Game Development

An array whose elements are references to class instances allocated separately on the heap.

A class array stores references to objects, not their data inline. Creating the array leaves its elements null; each object must be allocated separately. Their locations are not guaranteed to be contiguous, making cache-line placement harder to predict than with an array of structs. section 2.5

Coins flying to the UI

For a coin-pickup animation, each coin needs a current position, target position, and velocity. A CoinClass array can hold references to these objects, but each element must be initialized with new. When all fields are used together, a struct array offers contiguous storage; data-oriented designs often instead separate data into arrays. 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];

Compare the matching CoinStruct and CoinClass definitions and their array declarations. section 2.5

How High Performance Unity Game Development covers it

How deep it goes
Explains allocation, reference storage, and cache-locality implications without quantifying performance.
Examples
Uses a coin-pickup animation with current and target positions and velocity.
What it assumes
Assumes familiarity with arrays and data locality, while explaining how class and struct data are stored.
What you can do after
Evaluate class-array allocation and locality against contiguous struct arrays for data used together.
How it connects
Connects arrays of classes with arrays of structs, data locality, and cache misses.

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.