Skip to content

Instantly share code, notes, and snippets.

@nojaf
Created December 24, 2013 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nojaf/8112731 to your computer and use it in GitHub Desktop.
Save nojaf/8112731 to your computer and use it in GitHub Desktop.
Comparing the number of bytes and the time to create them when using a string or a Binary Formatter
class Program
{
static void Main(string[] args)
{
Random _rand = new Random();
List<Player> players = new List<Player>();
for (int i = 0; i < 20000; i++)
{
players.Add(new Player()
{
Id = i,
X = _rand.NextDouble() * _rand.Next(0, 800),
Y = _rand.NextDouble() * _rand.Next(0, 480)
});
}
Stopwatch sw = new Stopwatch();
BinaryFormatter formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, players);
byte[] bBytes = stream.ToArray();
sw.Stop();
Console.WriteLine("Bytes = " + bBytes.Length + " in, " + sw.Elapsed);
sw.Reset();
sw.Start();
string joined = string.Join(",", players);
byte[] sBytes = Encoding.ASCII.GetBytes(joined);
sw.Stop();
Console.WriteLine("String = " + sBytes.Length + " , in " + sw.Elapsed);
Console.Read();
}
}
[Serializable]
class Player
{
public int Id { get; set; }
public double X { get; set; }
public double Y { get; set; }
public override string ToString()
{
return Id + ";" + X + ";" + Y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment