Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Smurf-IV opened this issue Aug 1, 2019 · 1 comment
Open

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

Smurf-IV opened this issue Aug 1, 2019 · 1 comment

Comments

@Smurf-IV
Copy link

Smurf-IV commented Aug 1, 2019

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();
    }
@Smurf-IV
Copy link
Author

Smurf-IV commented Aug 1, 2019

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;
    }

Smurf-IV pushed a commit to Smurf-IV/LinqFaster that referenced this issue Aug 1, 2019
- Fix code to make it appear "As fast" Via the use of the "Coming out faster" acum = accum + nextVal method
- Add ReadOnlySpan to `SumF` api's
Smurf-IV pushed a commit to Smurf-IV/LinqFaster that referenced this issue Aug 8, 2019
…er a span

Create jackmott#22: [Question] Span_FirstF and List_FirstF are slower than just calling foreach -> Why?
Span this jackmott#24: [Enhancement] DefaultIfEmptyF should be implemented
Add Span jackmott#25: [Enhancement] Please also target .net4.8 and Benchmark
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant