Duration of binary serialization increased after serialize and deserialize an object in json serialization

54 views Asked by At

I've used NewtonSoft.Json to serialize an object and save it into a file. This object contains the whole data of a project created in my software. I read this file (deserialize) and create my project object if needed later. Previously, I used Binary serialization for this purpose, but the problem was that I could not read a saved file on another computer, so I changed it to Json type serialization. I also used compression for the output file to decrease its size.

JSON Serialization:

string jsonString = JsonConvert.SerializeObject(project, setting: new JsonSerializer() { Formatting = Formatting.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
byte[] inputBytes = Encoding.UTF8.GetBytes(jsonString);
using (FileStream outputFS = new FileStream(savePath, FileMode.Create))
{
   using (GZipStream compressionStream = new GZipStream(outputFS, CompressionMode.Compress))
   {
       compressionStream.Write(inputeBytes, 0, inputBytes.Length);
   }
}

JSON Deserialization:

string jsonString = string.Empty;
using (FileStream inputFS = new FileStream(filePath, FileMode.Open))
{
   using (GZipStream decompressionStream = new GZipStream(inputFS, CompressionMode.Decompress))
   {
      using (MemoryStream outputStream = new MemoryStream())
      {
         byte[] outputBytes = new byte[4096];
         int bytesRead;
         while ((bytesRead = decompressionStream.Read(outputBytes, 0, outputBytes.Length)) > 0)
         {
            outputStream.Write(outputBytes, 0, bytesRead);
         }
         jsonString = Encoding.UTF8.GetString(outputStream.ToArray());
      }
   }
}
Project proj = JsonConvert.DeserializeObject<Project>(jsonString);

In some parts of my software, I have to create a deep copy (clone) from my project object. For this matter, I use BinaryFormatter using the below method:

public static T DeepCopy<T>(T other)
{
   using (MemoryStream ms = new MemoryStream())
   {
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Context = new StreamingContext(StreamingContextStates.Clone);
      formatter.Serialize(ms, other);
      ms.Position = 0;
      return (T)formatter.Deserialize(ms);
   }
}

Previously, using the binary saving method, creating the clone after reading a saved file was quick. Right now, after I read a JSON-type saved file, the cloning process takes a lot of time. I checked the project object as much as I could and there is no difference before saving and after reading (at least anything visual is the same). Does anyone know the reason that caused this delay in cloning after reading the project object?

0

There are 0 answers