jackmott / LinqFaster

Linq-like extension functions for Arrays, Span<T>, and List<T> that are faster and allocate less.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Bug] Span SumF is slower than a for loop over a span

Smurf-IV opened this issue · comments

image

    [Benchmark]
    public int IntSpanESumLinq()
    {
        int val = 0;
        foreach (int i in intArray.AsSpan())
        {
            val += i;
        }
        return val;
    }

    [Benchmark]
    public int IntSpanFSumLinq()
    {
        int val = 0;
        Span<int> span = intArray.AsSpan();
        for (int index = 0; index < span.Length; index++)
        {
            val += span[index];
        }

        return val;
    }

    [Benchmark]
    public int IntSpanSumFast()
    {
        return intArray.AsSpan().SumF();
    }

Fixed:
image

    [Benchmark]
    public int IntSpanSumFor()
    {
        int val = 0;
        Span<int> span = intArray.AsSpan();
        for (int index = 0; index < span.Length; index++)
        {
            val += span[index];
        }

        return val;
    }

    [Benchmark]
    public int IntSpanSumFast()
    {
        return intArray.AsSpan().SumF();
    }

Via the use of the "Coming out faster" acum = accum + nextVal method

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static T SumF<P, T>(this P p, Span<T> source)
        where P : INumericPolicy<T>
    {
        if (source == null)
        {
            throw Error.ArgumentNull(nameof(source));
        }
        T a = p.Zero();
        checked
        {
            for (int index = 0; index < source.Length; index++)
            {
                a = p.Add(a, source[index]);
            }
        }
       return a;
    }