Last active
February 17, 2020 17:52
-
-
Save xoofx/b59c267df0aca550bc3585eb6eaddf60 to your computer and use it in GitHub Desktop.
Feedback on dynamic Tuples experiment https://github.com/YohDeadfall/Yoh.Tuples
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
// Feedback on https://github.com/YohDeadfall/Yoh.Tuples | |
/* | |
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | | |
|---------------- |----------:|---------:|---------:|-------:|------:|------:|----------:| | |
| TestSimpleTuple | 50.02 ns | 0.423 ns | 0.396 ns | 0.0229 | - | - | 192 B | | |
| TestYohTuple | 739.97 ns | 1.783 ns | 1.580 ns | 0.1822 | - | - | 1528 B | | |
*/ | |
using System; | |
using System.Runtime.CompilerServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace Yoh.Tuples.Benchmarks | |
{ | |
/// <summary> | |
/// Simple tuple using an internal array of value (ulong+object) | |
/// It works well for storing all primitive types (e.g int, float, string...), reference types | |
/// or any value type that is less than 64 bits (so including IntPtr). | |
/// Work less well if you store a value type that has generic references as it would require boxing for each value. | |
/// </summary> | |
public class SimpleTuple | |
{ | |
private TupleData[] _datas; | |
public void AddValue<T>(T value) | |
{ | |
int index = -1; | |
if (_datas == null) | |
{ | |
_datas = new TupleData[1]; | |
index = 0; | |
} | |
else | |
{ | |
index = _datas.Length; | |
var newDatas = new TupleData[index + 1]; | |
Array.Copy(_datas, newDatas, _datas.Length); | |
_datas = newDatas; | |
} | |
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>() || Unsafe.SizeOf<T>() > 8) | |
{ | |
_datas[index].Object = value; | |
} | |
else | |
{ | |
Unsafe.As<ulong, T>(ref _datas[index].Value) = value; | |
} | |
} | |
private struct TupleData | |
{ | |
public ulong Value; | |
public object Object; | |
} | |
} | |
[MemoryDiagnoser] | |
public class Program | |
{ | |
[Benchmark] | |
public void TestSimpleTuple() | |
{ | |
var tuple = new SimpleTuple(); | |
tuple.AddValue(1); | |
tuple.AddValue("test"); | |
tuple.AddValue('Q'); | |
} | |
[Benchmark] | |
public void TestYohTuple() | |
{ | |
var tuple = new Tuple(); | |
tuple.AddValue(1); | |
tuple.AddValue("test"); | |
tuple.AddValue('Q'); | |
} | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<Program>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment