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

Optimizing Save File Size and Disk Usage

Learners will implement compression and binary serialization techniques to minimize disk footprint and improve performance on hardware with limited storage.

In this lesson, you will learn how to shrink your save files and reduce disk I/O overhead by combining binary serialization with data compression techniques.

As your game’s save data grows, relying on plain-text formats like JSON can lead to massive files that strain storage and increase load times. To optimize this, we shift from human-readable text to binary streams and wrap that data in a compression algorithm.

Binary Serialization vs. Compression

While binary serialization (using BinaryFormatter or custom BinaryWriter) removes the overhead of text formatting (like repetitive keys and braces), the file size is still proportional to the raw data. To truly minimize the footprint, we pass the resulting byte array through a compression stream, such as GZipStream. This is particularly effective for save files containing redundant patterns or long sequences of similar values.

Implementation Strategy

The process involves three steps: serializing your data to a binary stream, compressing that stream, and writing the final compressed bytes to disk.

using System.IO;
using System.IO.Compression;

public void SaveCompressed(object data, string path)
{
    using (FileStream fs = new FileStream(path, FileMode.Create))
    using (GZipStream compressionStream = new GZipStream(fs, CompressionMode.Compress))
    {
        // Serialize your binary data directly into the compression stream
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(compressionStream, data);
    }
}

By wrapping the FileStream in a GZipStream, the data is compressed on-the-fly before hitting the disk. When loading, you simply reverse the flow: read the file, wrap it in a GZipStream set to Decompress, and deserialize the output back into your game objects.

Performance Considerations

Keep in mind that compression is a trade-off. While it saves disk space and reduces I/O bandwidth, it consumes CPU cycles to compress and decompress the data. Always perform these operations asynchronously to prevent frame stutters, especially if your save file is large. On mobile devices with limited storage, the balance usually tilts heavily in favor of compression to ensure a smaller footprint without sacrificing performance.

Key Takeaway: Combine binary serialization with GZip compression to significantly reduce disk footprint and accelerate I/O operations by minimizing the amount of data written to physical storage.