Maarten
Maarten

Reputation: 53

Deserialization slow performance in Unity

I am making a 3D simulator in Unity.
For this simulator I need some data which I store in a Serializable object.
This object is defined in a DLL file that I made.
I deserialize it with this code:

public class myObject
{
    static public myObject LoadFromFile(String Path)
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        System.IO.FileStream FS = new System.IO.FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
        myObject Result = BF.Deserialize(FS) as myObject;
        FS.Close();
        return Result;
    }
}

My unity program has a reference to the class library containing the definition of 'myObject'.
If I run the deserialization function from Unity this process takes 35.080 seconds.

If I run this in a windows application, which I created for testing purpose and refers to the same class library and opens the same file, this process takes only 0.260 seconds.

It takes a long time in Unity even if I run this process asynchronously.

I wonder why it takes that much longer when I run this code from Unity? and if there is anything that I can do about this?

Thanks in advance,
Maarten

Upvotes: 4

Views: 2281

Answers (2)

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

I dont know why this happens but one thing you can try is to implement the ISerializable interface, serialize your members yourself and see if unity is still as slow.

You will need to implement GetObjectData and a protected constructor taking a SerializationInfo and a StreamingContext. GetObjectData for putting the object on the serialization stream and the contructor for....uhm....constructing.

public class MyObject : ISerializable
{
  private bool somemember;

  protected Complaint(SerializationInfo info, StreamingContext context)
  {
    somemember = info.GetBoolean("b");
  }

  [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
  public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("b", somemember);
  }
}

Hope this helps!

Upvotes: 2

Jay
Jay

Reputation: 175

I don't fully understand your Question. The class you want to access is inside your .dll file? If so – it doesn't matter where your class definition is located at. Where and how is your data stored? If you want to store data permanently on your hard drive you could easily use Json.NET and store your data as a .json file. From which method and when do you try to load your data inside unity?

Besides, if you open a file stream you should also close it again, when you're done reading from it. You could also take a look at some coding conventions like here

Upvotes: 0

Related Questions