[Bug] Span SumF is slower than a for loop over a span
Smurf-IV opened this issue · comments
Simon Coghlan commented
[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();
}
Simon Coghlan commented
[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;
}