Created
January 20, 2014 21:08
-
-
Save MrKWatkins/8529194 to your computer and use it in GitHub Desktop.
Comparison of two functions to convert an enum value to a byte, one using safe code, the other using unsafe code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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