J
Jack
Imagine if someone asked which of the follwing two methods of encoding
an integer into a byte array was quicker.
The purpose is in preparation for sending across a socket as part of a
'header'.
If you are curious, run the code yourself.
if(args.Length != 1)
{
Console.WriteLine("Usage: {0} <iterations>",
System.AppDomain.CurrentDomain.FriendlyName);
return;
}
int[] size = new int[Convert.ToInt32(args[0])];
for(int i = 0; i < size.Length; i++)
size = i;
HiPerfTimer timer = new HiPerfTimer();
byte[] headerBuf = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
// convert the int to a byte array in network byte
order
headerBuf = BitConverter.GetBytes(size);
}
timer.Stop();
long bitConvert = timer.usec;
byte[] bas = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
bas = new byte[4];
bas[0] = (byte)(size >> 24);
bas[1] = (byte)(size >> 16);
bas[2] = (byte)(size >> 8);
bas[3] = (byte)(size);
}
timer.Stop();
long bitShift = timer.usec;
Console.WriteLine("BitShift method on sample of length {0}
took {1} microseconds", size.Length, bitShift );
Console.WriteLine("BitConverter method on sample of length
{0} took {1} microseconds", size.Length, bitConvert );
an integer into a byte array was quicker.
The purpose is in preparation for sending across a socket as part of a
'header'.
If you are curious, run the code yourself.
if(args.Length != 1)
{
Console.WriteLine("Usage: {0} <iterations>",
System.AppDomain.CurrentDomain.FriendlyName);
return;
}
int[] size = new int[Convert.ToInt32(args[0])];
for(int i = 0; i < size.Length; i++)
size = i;
HiPerfTimer timer = new HiPerfTimer();
byte[] headerBuf = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
// convert the int to a byte array in network byte
order
headerBuf = BitConverter.GetBytes(size);
}
timer.Stop();
long bitConvert = timer.usec;
byte[] bas = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
bas = new byte[4];
bas[0] = (byte)(size >> 24);
bas[1] = (byte)(size >> 16);
bas[2] = (byte)(size >> 8);
bas[3] = (byte)(size);
}
timer.Stop();
long bitShift = timer.usec;
Console.WriteLine("BitShift method on sample of length {0}
took {1} microseconds", size.Length, bitShift );
Console.WriteLine("BitConverter method on sample of length
{0} took {1} microseconds", size.Length, bitConvert );