Skip to content

Validate implementations performance #10

@FelixCCWork

Description

@FelixCCWork

Check for reference Option implementation from https://github.com/louthy/language-ext
Comment about perf: louthy/language-ext#860

Stripped down version of Option (LinqPad)

#load "BenchmarkDotNet"

void Main()
{
	RunBenchmark();  // Uncomment this line to initiate benchmarking.
}

[Benchmark]
public int DefaultTest()
{
	return 3 + 4;
}

[Benchmark]
public int ResultTest()
{
	Result<int> result = Sum(3, 4);

	return result.Value;
}

Result<int> Sum(int valueA, int valueB)
{
	if (valueA < 0 || valueB < 0)
		return MyFunctional.None;

	return valueA + valueB;
}

static class MyFunctional
{
	/// <summary>
	/// 'No value' state of Result T.
	/// </summary>
	[Pure]
	public static Fail<Unit> None => default;

	/// <summary>
	/// Create a `Some` of `T`
	/// </summary>
	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static Result<T> Some<T>(T value) => new Result<T>(value);

	/// <summary>
	/// Create an `Result` of `T`
	/// </summary>
	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static Result<T> Result<T>(T? value) =>
		value is null
			? default
			: new Result<T>(value);

	/// <summary>
	/// Create an `Result` of `T`
	/// </summary>
	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static Result<T> Result<T>(T? value) where T : struct =>
		value.HasValue
			? new Result<T>(value.Value)
			: default;
}

struct Result<T>
{
	public T Value { get; private init; }
	
	public bool IsSome {get; private init; }

	public static readonly Result<T> None = default;

	public static Result<T> Some(T value) => new Result<T>() { Value = value };

	internal Result(T value)
	{
		Value = value;
		IsSome = true;
	}

	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static implicit operator Result<T>(T? value) => MyFunctional.Result(value);

	/// <summary>
	/// Implicit conversion operator from None to Result〈T〉
	/// </summary>
	/// <param name="a">None value</param>
	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static implicit operator Result<T>(Fail<Unit> a) =>
		default;

	/// <summary>
	/// Implicit conversion operator from None to Result〈T〉
	/// </summary>
	/// <param name="a">None value</param>
	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static implicit operator Result<T>(in Unit fail) =>
		default;
}

struct Fail<T>
{
	public static readonly Fail<T> None = default;
}

readonly struct Unit
{
	public static readonly Unit Default = default;

	[Pure]
	public static Unit Empty => default;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions