Course contentsShow
← Unity Game Development
Lesson 749 of 82811. Performance and Data PersistenceFree lesson

Optimizing Performance with Binary Serialization

Convert your game state into a compact binary format using System.Runtime.Serialization to significantly reduce file size and increase read-write processing speeds.

In this lesson, you will learn how to bypass the overhead of text-based formats like JSON by using binary serialization to shrink your save data and accelerate I/O operations.

Moving Beyond Text

While JsonUtility is human-readable, it is inherently inefficient for large game states. Every number is converted into a string (e.g., 12.34567 takes 8 bytes as text), and the parser must perform heavy character-by-character analysis to reconstruct your objects. Binary serialization, by contrast, stores data in its raw, machine-level format. A single float occupies exactly 4 bytes regardless of its value, leading to significantly smaller file sizes and near-instantaneous read/write speeds.

Implementing BinaryFormatter

To implement this, you leverage System.Runtime.Serialization.Formatters.Binary. First, ensure your data class is marked with the [System.Serializable] attribute. This allows the formatter to traverse your object graph and translate fields directly into a stream of bytes.

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public void SaveGame(GameState data, string path) {
    BinaryFormatter formatter = new BinaryFormatter();
    using (FileStream stream = new FileStream(path, FileMode.Create)) {
        formatter.Serialize(stream, data);
    }
}

Why This Wins for Performance

When loading a massive save file, JSON parsers must allocate memory for every string key and value, causing significant Garbage Collection pressure. Binary serialization writes and reads the raw byte-buffer directly into your class structure. This avoids the intermediary string allocation entirely, which is vital when you need to minimize the performance impact of saving state during gameplay or when handling complex, nested data structures that would otherwise bloat a text file.

Keep in mind that binary files are not human-readable, so debugging requires a tool to inspect the byte stream, but for production-level performance, the trade-off in efficiency is unparalleled.

Key Takeaway: Binary serialization reduces disk footprint and eliminates string-parsing overhead, transforming your save system into a high-performance, memory-efficient process.