Last active
July 19, 2018 17:46
-
-
Save adamsitnik/2b0eedf5c822e7c726d944d219bb301c to your computer and use it in GitHub Desktop.
Consumer
This file contains 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.Runtime.CompilerServices; | |
using System.Threading; | |
namespace Benchmarks | |
{ | |
public class Consumer | |
{ | |
private volatile byte byteHolder; | |
private volatile sbyte sbyteHolder; | |
private volatile short shortHolder; | |
private volatile ushort ushortHolder; | |
private volatile int intHolder; | |
private volatile uint uintHolder; | |
private volatile bool boolHolder; | |
private volatile char charHolder; | |
private volatile float floatHolder; | |
private double doubleHolder; | |
private long longHolder; | |
private ulong ulongHolder; | |
public static object objectHolder; | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public void Consume<T>(in T value) | |
{ | |
if (typeof(T) == typeof(byte)) | |
byteHolder = (byte)(object)value; | |
else if (typeof(T) == typeof(sbyte)) | |
sbyteHolder = (sbyte)(object)value; | |
else if (typeof(T) == typeof(short)) | |
shortHolder = (short)(object)value; | |
else if (typeof(T) == typeof(ushort)) | |
ushortHolder = (ushort)(object)value; | |
else if (typeof(T) == typeof(int)) | |
intHolder = (int)(object)value; | |
else if (typeof(T) == typeof(uint)) | |
uintHolder = (uint)(object)value; | |
else if (typeof(T) == typeof(bool)) | |
boolHolder = (bool)(object)value; | |
else if (typeof(T) == typeof(char)) | |
charHolder = (char)(object)value; | |
else if (typeof(T) == typeof(float)) | |
floatHolder = (float)(object)value; | |
else if (typeof(T) == typeof(double)) | |
Volatile.Write(ref doubleHolder, (double)(object)value); | |
else if (typeof(T) == typeof(long)) | |
Volatile.Write(ref longHolder, (long)(object)value); | |
else if (typeof(T) == typeof(ulong)) | |
Volatile.Write(ref ulongHolder, (ulong)(object)value); | |
else if (default(T) == null) | |
objectHolder = (object) value; | |
else | |
ValueTypesConsumer(value); // non-primitive value types | |
} | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
private void ValueTypesConsumer<T>(in T value) { } | |
} | |
public class Sample | |
{ | |
public void Iterate<T>(T[] array) | |
{ | |
var consumer = new Consumer(); | |
for (int i = 0; i < array.Length; i++) | |
{ | |
consumer.Consume<T>(in array[i]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment