liveBook · Manning

String

As explained in High Performance Unity Game Development

A string is a sequence of text characters represented as a value that can be stored and manipulated by a program.

A string is an array of characters. Storing one in a struct does not store its character data inside the struct: the string is allocated on the heap, even if the struct itself is on the stack. Assigning a new value allocates another string; the old one remains until the garbage collector frees it. section 2.4.3

Listing 2.19 Struct with a string
public struct Enemy
{
    public string Name;
    public Vector2 Position;
    public Vector2 Direction;
    public float Velocity;
}

The Enemy struct places a string field beside position, direction, and velocity data. section 2.4.3

Changing an enemy name

Assigning Enemy.Name = "Enemy Name" allocates string storage. Changing it to "New Name" allocates another string, while the previous one waits for garbage collection. Consider this allocation behavior when deciding whether a string belongs in performance-sensitive struct data. section 2.4.3

How High Performance Unity Game Development covers it

How deep it goes
Traces string storage and reassignment to heap allocation and garbage-collector reclamation, without detailing allocation-avoidance alternatives.
Examples
Uses an Enemy struct whose Name is assigned and changed to illustrate allocation and delayed reclamation.
What it assumes
Assumes familiarity with cache lines and stack-versus-heap placement rather than teaching cache behavior from zero.
What you can do after
Evaluate string fields in structs by anticipating heap allocation when assigning or changing a name.
How it connects
Connects strings with arrays, structs, heap allocation, stack storage, garbage collection, and data locality.

Also explained in

Compare how 28 books explain string →

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.