Page 1 of 1

Storing object data in a file - C#

Posted: Wed Apr 18, 2012 3:05 am
by mattykins
Hey everyone, i've been making progress in C#. But i've come to the conclusion that i must write more efficient code LOL. In ConsoleCraft When the world generates it generates 256*256*2 Objects. Which is roughly 131,000 objects, each of those objects contains an array of integers or tiles([60, 25]). So (256*256*2)*(60*25) Which is rouglhly 196,600,000 integers, if each integer is given 4 bytes of data that becomes... ok enough with the calculations but basically it takes a huge toll on the computer, roughly 750mb of integers. I have a feeling this size would go down a lot an relieve a lot of stress on the computer if i could just store all of the object data inside of a file. Some people suggeested serialization but i cannot find a good tutorial nor MDSN page about it. So i was hoping all of you could enlighten me on how to do this :) Thanks everyone!

Re: Storing object data in a file - C#

Posted: Wed Apr 18, 2012 10:50 am
by Chris
As far as I've learned, serialization lets you convert an object instance into bytes, which can be interpreted as a string or other data types, and also be converted back to an object.

The thing that might be a little hard to grasp is the way you have to interpret the data. You could save it as XML, I would however advice using JSON.

Code: Select all

using System.Web.Script.Serialization.JavaScriptSerializer; 

Code: Select all

class myClass
{
    public string Lol;
    public string Foo;
}

var myObject = new myClass { Lol = "haha", Foo = "bar"  };

JavaScriptSerializer Serializer = new JavaScriptSerializer();
string mySerealizedObject = Serializer.Serialize(myObject); 
output:

Code: Select all

"{\"Lol\":\"haha\",\"Foo\":\"bar\"}" 

Re: Storing object data in a file - C#

Posted: Thu Apr 19, 2012 2:24 am
by mattykins
When i serialize an object does that automatically write the current state of that object when serialized to a file?

Re: Storing object data in a file - C#

Posted: Thu Apr 19, 2012 5:26 am
by Jackolantern
Yep! That is the main point to serialization :)

Re: Storing object data in a file - C#

Posted: Thu Apr 19, 2012 8:47 am
by Chris
mattykins wrote:When i serialize an object does that automatically write the current state of that object when serialized to a file?
By the looks of it the Json.NET library has built in functionality for this. http://json.codeplex.com/