Binary serialization, IFormatter: use a new one every time or save it in a field?

Using binary formatting for the first time in .net C #

The code from MSDN is as follows:

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 if I should store the IFormatter in a field in my class and use it again and again, or should I do it as above and create a new instance each time I save / load?

I noticed that this is not IDisposable .

+4
source share
1 answer

When creating a BinaryFormatter very little overhead, most of the properties that it sets in the constructor are enum s, 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 intend to reuse it, you will need to synchronize access to the Serialize and Deserialize methods so that they are thread safe.

+6
source

Source: https://habr.com/ru/post/1480727/


All Articles