Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary serialization, IFormatter: use a new one each time or store one in a field?

Using binary formatting for 1st time in .net C#

Code from MSDN is like this:

 IFormatter formatter = new BinaryFormatter();
 Stream stream = new FileStream("MyFile.lvl", FileMode.Create, FileAccess.Write,FileShare.None);
 formatter.Serialize(stream, Globals.CurrentLevel);
 stream.Close();

Just wondering should I store an IFormatter in a field in my class and use it over and over again or should I do as above and instantiate a new one every time I save/load something?

I noticed it is not IDisposable.

like image 538
Guye Incognito Avatar asked May 14 '13 13:05

Guye Incognito


People also ask

How does binary serialization work?

In binary serialization, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

How does binary formatter work?

The class BinaryFormatter in C# performs the actions of “serialization” and “deserialization” of binary data. It takes simple data structures such as integers (int), decimal numbers (float), and collections of letters and numbers (string) and can convert them into a binary format.

Is binary serialization safe?

Microsoft warns against using BinaryFormatter (they write that there is no way to make the de-serialization safe). Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy.

What is a binary formatter?

BinaryFormatter is used to serialize an object (meaning it converts it to one long stream of 1s and 0s), and deserialize it (converting that stream back to its usual form with all data intact), and is typically used with to save data to the hard disk so it can be loaded again after the game is closed and started up ...


1 Answers

There's very little overhead in re-creating a BinaryFormatter, most of the properties it sets in the constructor are enums, see here (thanks to Reflector):

public BinaryFormatter()
{
    this.m_typeFormat = FormatterTypeStyle.TypesAlways;
    this.m_securityLevel = TypeFilterLevel.Full;
    this.m_surrogates = null;
    this.m_context = new StreamingContext(StreamingContextStates.All);
}

If you were going to re-use it though, you'd need to synchronize access to the Serialize and Deserialize methods to keep them thread-safe.

like image 58
mattytommo Avatar answered Oct 13 '22 07:10

mattytommo