OneOf icon indicating copy to clipboard operation
OneOf copied to clipboard

[Perf] Redundant checks in a few places

Open RezaJooyandeh opened this issue 4 years ago • 1 comments

A few of the methods are double checking which index is set or making redundant nested calls that could be removed eg:

public OneOf<TResult, T1, T2> MapT0<TResult>(Func<T0, TResult> mapFunc)
{
    if (mapFunc == null)
    {
        throw new ArgumentNullException(nameof(mapFunc));
    }
    return _index switch
    {
        0 => mapFunc(AsT0), // could be: mapFunc(_value0)
        1 => AsT1, // _value1
        2 => AsT2, // _value2
        _ => throw new InvalidOperationException()
    };
}

or

public bool TryPickT0(out T0 value, out OneOf<T1, T2> remainder)
{
    value = IsT0 ? AsT0 /*_value0*/ : default;
    remainder = _index switch
    {
        0 => default,
        1 => AsT1, // _value1
        2 => AsT2, // _value2
        _ => throw new InvalidOperationException()
    };
    return isT0;
}

Considering that AsTn properties are doing extra checks and not simple props, it won't allow compiler to optimize them either.

I am more than happy to send a PR, if this change is something you would like to incorporate.

RezaJooyandeh avatar Jul 18 '21 00:07 RezaJooyandeh

You probably want to put together some Benchmarks to show that this is actually an issue (and if so, what the actual runtime impact might be). It's entirely possible that the compiler already optimizes these out, or that the JIT does it later on.

bevanweiss avatar Jan 13 '25 03:01 bevanweiss