Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MrKWatkins
Created January 21, 2014 22:34
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 MrKWatkins/8549860 to your computer and use it in GitHub Desktop.
Save MrKWatkins/8549860 to your computer and use it in GitHub Desktop.
Comparison of two functions to convert a long to a byte array, one using safe code, the other using unsafe code.
using System;
using System.Diagnostics;
namespace TestCSharpConsoleApplication
{
internal static class Program
{
private static void Main()
{
const int iterations = 500000000;
var stopwatch = new Stopwatch();
var value = RandomLong();
Console.WriteLine("Iterations: " + iterations);
Console.WriteLine("Value: " + value);
stopwatch.Start();
var bytes = RunSafeBytesToLong(iterations, value);
stopwatch.Stop();
Console.WriteLine("Safe (took {0:f2}ms): [{1}]", stopwatch.ElapsedMilliseconds, string.Join(", ", bytes));
stopwatch.Reset();
stopwatch.Start();
bytes = RunUnsafeBytesToLong(iterations, value);
stopwatch.Stop();
Console.WriteLine("Unsafe (took {0:f2}ms): [{1}]", stopwatch.ElapsedMilliseconds, string.Join(", ", bytes));
Console.Read();
}
// Have another method for timing each method rather than pass in a delegate as the dynamic function call will dwarf the time of the call itself...
private static byte[] RunSafeBytesToLong(int iterations, long value)
{
byte[] bytes = null;
for (var f = 0; f < iterations; f++)
{
bytes = SafeLongToBytes(value);
}
return bytes;
}
private static byte[] RunUnsafeBytesToLong(int iterations, long value)
{
byte[] bytes = null;
for (var f = 0; f < iterations; f++)
{
bytes = UnsafeLongToBytes(value);
}
return bytes;
}
private static byte[] SafeLongToBytes(long value)
{
var bytes = new byte[8];
bytes[0] = (byte) value;
bytes[1] = (byte) (value >> 8);
bytes[2] = (byte) (value >> 16);
bytes[3] = (byte) (value >> 24);
bytes[4] = (byte) (value >> 32);
bytes[5] = (byte) (value >> 40);
bytes[6] = (byte) (value >> 48);
bytes[7] = (byte) (value >> 56);
return bytes;
}
private static unsafe byte[] UnsafeLongToBytes(long value)
{
var bytes = new byte[8];
fixed (byte* pointer = bytes)
{
*(long*)pointer = value;
}
return bytes;
}
private static long RandomLong()
{
var randomDouble = new Random().NextDouble() - 0.5;
return (long) (randomDouble*long.MaxValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment