Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Comparison of two functions to convert an enum value to a byte, one using safe code, the other using unsafe code.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace TestCSharpConsoleApplication
{
internal static class Program
{
private static void Main()
{
const int iterations = 100000000;
var stopwatch = new Stopwatch();
var enumValues = BuildEnumValues();
stopwatch.Start();
RunSafeToByte(enumValues, iterations);
stopwatch.Stop();
Console.WriteLine("Safe = {0:f2}ms", stopwatch.ElapsedMilliseconds);
stopwatch.Reset();
stopwatch.Start();
RunUnsafeToByte(enumValues, iterations);
stopwatch.Stop();
Console.WriteLine("Unsafe = {0:f2}ms", stopwatch.ElapsedMilliseconds);
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 long RunSafeToByte(ConsoleColor[] enumValues, int iterations)
{
// Keeping a count so we actually do something with the return value - don't want the JITter optimising stuff away.
var count = 0L;
for (var f = 0; f < iterations; f++)
{
for (var g = 0; g < enumValues.Length; g++)
{
count += SafeConvert(enumValues[g]);
}
}
return count;
}
private static long RunUnsafeToByte(ConsoleColor[] enumValues, int iterations)
{
var count = 0L;
for (var f = 0; f < iterations; f++)
{
for (var g = 0; g < enumValues.Length; g++)
{
count += UnsafeConvert(enumValues[g]);
}
}
return count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Force inlining in case one gets inlined and the other doesn't...
private static byte SafeConvert(ConsoleColor value)
{
return (byte) value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe static byte UnsafeConvert(ConsoleColor value)
{
return *(byte*) &value;
}
private static ConsoleColor[] BuildEnumValues()
{
return (ConsoleColor[]) Enum.GetValues(typeof (ConsoleColor));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.