I\'m currently optimizing an application, one of the operations that is done very often is reading and writing binary. I need 2 types of functions:
Set(byte[] ta
Using Marc Gravell's Set1
to Set4
and the Set5
below, I get the following numbers on my machine:
Set1: 197ms
Set2: 102ms
Set3: 604ms
Set4: 68ms
Set5: 55ms <==== pointer magic ;-p
Code:
unsafe static void Set5(byte[] target, int index, int value)
{
fixed (byte* p = &target[index])
{
*((int*)p) = value;
}
}
Of course, it gets much faster when the byte array isn't pinned on each iteration but only once:
Set6: 10ms (little endian)
Set7: 85ms (big endian)
Code:
if (!BitConverter.IsLittleEndian)
{
throw new NotSupportedException();
}
watch = Stopwatch.StartNew();
fixed (byte* p = buffer)
{
for (int i = 0; i < LOOP; i++)
{
*((int*)(p + INDEX)) = VALUE;
}
}
watch.Stop();
Console.WriteLine("Set6: " + watch.ElapsedMilliseconds + "ms");
watch = Stopwatch.StartNew();
fixed (byte* p = buffer)
{
for (int i = 0; i < LOOP; i++)
{
*((int*)(p + INDEX)) = System.Net.IPAddress.HostToNetworkOrder(VALUE);
}
}
watch.Stop();
Console.WriteLine("Set7: " + watch.ElapsedMilliseconds + "ms");