Tricks of Serialization in Unity/C#
Don’t use XmlSerializer
- XmlSerializer + StringWriter is sloooooow
- XmlSerializer does NOT require [Serializable]
- XmlSerializer does NOT support ISerializable
Use BinaryFormatter + MemoryStream
. It’s fast and customizable.
Use System.Diagnostics.Stopwatch
for simple profile.
Use Encoding.ASCII.GetString()
to convert MemorySteam
to string
Use Convert.ToBase64String
for binary data that contains ‘\0’
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, target);
string result = Convert.ToBase64String(stream.ToArray());
//string result = Encoding.ASCII.GetString(stream.ToArray());
Another “trick” for BinaryFormatter in Unity/iOS :
http://answers.unity3d.com/questions/30930/why-did-my-binaryserialzer-stop-working.html
// Just add the following line to the Awake() function of the MonoBehaviour
// script and the BinaryFormatter should work fine on iOS.
// Forces a different code path in the BinaryFormatter that doesn't rely on
// run-time code generation (which would break on iOS).
Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes")