0
0
Unityframework~8 mins

Variables and serialization in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: Variables and serialization
MEDIUM IMPACT
This concept affects how data is stored and loaded in Unity, impacting load times and memory usage during gameplay.
Saving and loading game state variables
Unity
[System.Serializable]
public class PlayerData {
    public int health;
    public string playerName;
    public List<Item> inventory;
}

// Using Unity's JsonUtility for serialization
string json = JsonUtility.ToJson(playerData);
File.WriteAllText(path, json);
JsonUtility is faster, produces smaller files, and can be used asynchronously to avoid blocking the main thread.
📈 Performance GainReduces blocking time to tens of milliseconds; smaller file size improves load speed.
Saving and loading game state variables
Unity
public class PlayerData {
    public int health;
    public string playerName;
    public List<Item> inventory;
}

// Using BinaryFormatter for serialization
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(path);
bf.Serialize(file, playerData);
file.Close();
BinaryFormatter is slow, insecure, and produces large files; it also blocks the main thread during serialization.
📉 Performance CostBlocks main thread for hundreds of milliseconds on large data; large file size increases load time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
BinaryFormatter serializationN/AN/AN/A[X] Bad
Unity JsonUtility serializationN/AN/AN/A[OK] Good
Rendering Pipeline
Serialization affects the loading phase before rendering starts. Efficient serialization reduces the time spent reading and parsing data, allowing faster scene setup and rendering.
Loading
Memory Allocation
⚠️ BottleneckData parsing and file I/O during load
Optimization Tips
1Use Unity's JsonUtility for faster and smaller serialization.
2Avoid blocking the main thread by using asynchronous serialization.
3Minimize serialized data size to reduce load time and memory use.
Performance Quiz - 3 Questions
Test your performance knowledge
Which serialization method in Unity is generally faster and produces smaller files?
AUnity's JsonUtility
BBinaryFormatter
CXML serialization
DManual byte array serialization
DevTools: Profiler
How to check: Open Unity Profiler, record while loading saved data, and check CPU usage and time spent in serialization functions.
What to look for: Look for long blocking times in serialization calls and high memory allocations during load.