In this lesson, you will learn how to evaluate the performance and usability trade-offs of JSON, XML, and Binary serialization to choose the optimal storage strategy for your game’s specific data requirements.
When persisting data in Unity, there is no "one-size-fits-all" solution. Your choice depends on the frequency of access, the complexity of your data structures, and whether the file needs to be human-readable.
JSON (JavaScript Object Notation)
JSON is the industry standard for configuration files and simple save data. It is lightweight, human-readable, and supported natively via JsonUtility or third-party libraries like Newtonsoft.Json.
- Pros: Easy to debug; works great for small to medium-sized data.
- Cons: Becomes slow with massive datasets; lacks native support for complex class hierarchies without custom converters.
XML (Extensible Markup Language)
XML uses a tree-based structure and is common in enterprise systems or legacy web services.
- Pros: Highly descriptive and standard-compliant.
- Cons: Very verbose, leading to larger file sizes compared to JSON or Binary. The parsing overhead is significantly higher, which can cause frame stutters if performed on the main thread during gameplay.
Binary Serialization
Binary serialization converts objects directly into a stream of bytes. This is often implemented using System.Runtime.Serialization.Formatters.Binary or by writing custom BinaryWriter logic.
- Pros: Extremely performant. Files are tiny and difficult for users to edit (great for preventing save-file tampering).
- Cons: Not human-readable, making debugging difficult. It is also version-sensitive—if you change your class structure, old binary files may fail to load unless you implement robust versioning logic.
Strategic Selection
To decide, look at your requirements:
- Is it a moddable configuration file? Use JSON. The readability allows players to tweak values.
- Is it a large player save file (e.g., inventory, procedural map data)? Use Binary. It minimizes disk I/O and prevents GC spikes associated with string parsing.
- Does it require cross-platform standard interoperability? Use XML only if specifically required by external systems; otherwise, JSON is almost always superior for Unity performance.
Key Takeaway: Choose JSON for human-readable configuration and Binary for high-performance, large-scale data persistence to minimize CPU and storage overhead.