Skip to content

Instantly share code, notes, and snippets.

View ocoanet's full-sized avatar

Olivier Coanet ocoanet

View GitHub Profile
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Read<T>()
{
if (TypeCache<T>.CanUsePadding16)
return Unsafe.As<Padding16, T>(ref _valueStorage);
return (T)_defaultStorage;
}
public static class TypeCache<T>
| Method | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------------- |----------:|----------:|----------:|------:|------:|------:|------:|----------:|
| ReadWriteTyped | 0.6390 ns | 0.0005 ns | 0.0004 ns | 1.00 | - | - | - | - |
| ReadWriteSolution1 | 1.0009 ns | 0.0005 ns | 0.0004 ns | 1.57 | - | - | - | - |
| ReadWriteSolution2 | 0.9996 ns | 0.0007 ns | 0.0006 ns | 1.56 | - | - | - | - |
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Read<T>()
{
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>() && Unsafe.SizeOf<T>() <= 16)
return Unsafe.As<Padding16, T>(ref _valueStorage);
return (T)_defaultStorage;
}
| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------------- |----------:|----------:|----------:|------:|--------:|-------:|------:|------:|----------:|
| ReadWriteTyped | 0.6415 ns | 0.0008 ns | 0.0007 ns | 1.00 | 0.00 | - | - | - | - |
| ReadWriteBoxing | 4.3225 ns | 0.0385 ns | 0.0360 ns | 6.74 | 0.06 | 0.0057 | - | - | 24 B |
| ReadWriteSolution1 | 1.0003 ns | 0.0023 ns | 0.0020 ns | 1.56 | 0.00 | - | - | - | - |
public class PipelineStepEventTyped<T>
{
private T _value;
public void Write(T value) => _value = value;
public T Read() => _value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Read<T>()
{
if (typeof(T) == typeof(int)
|| typeof(T) == typeof(bool)
|| typeof(T) == typeof(byte)
|| typeof(T) == typeof(char)
|| typeof(T) == typeof(short)
|| typeof(T) == typeof(long)
|| typeof(T) == typeof(float)
// write
Unsafe.As<Padding16, T>(ref _valueStorage) = value;
// read
return Unsafe.As<Padding16, T>(ref _valueStorage);
public class PipelineStepEvent
{
private Padding16 _valueStorage;
private object _defaultStorage;
// Use _valueStorage to store small value types.
[StructLayout(LayoutKind.Explicit, Size = 16)]
private struct Padding16
{
public class PipelineStepEvent
{
private object _value;
public T Read<T>() => (T)_value;
public void Write<T>(T value) => _value = value;
}
IPipelineBuilder builder = CreatePipelineBuilder();
// create pipeline
var pipeline = builder.Build<Input1, Output1>(x => Step1(x), workerCount: 2)
.AddStep<Output2>(x => Step2(x), workerCount: 3)
.AddStep<Output3>(x => Step3(x), workerCount: 1)
.Create();
// use pipeline
var output3 = await pipeline.Execute(new Input1());