Skip to content

Commit 4864243

Browse files
authored
Merge pull request Cysharp#148 from prozolic/LongCount
Improve LongCount(predicate) from array performance
2 parents e3150e5 + bc38aae commit 4864243

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

sandbox/Benchmark/Benchmarks/AllAnyPredicateWithCapturedLambda.cs

+31
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,34 @@ public int Linq()
110110
return _nums.Count(i => i <= _target);
111111
}
112112
}
113+
114+
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
115+
public class LongCountPredicateWithCapturedLambda
116+
{
117+
[Params(10, 100, 1000, 10000)]
118+
public int N;
119+
120+
int[] _nums = default!;
121+
int _target;
122+
123+
[GlobalSetup]
124+
public void Setup()
125+
{
126+
_nums = Enumerable.Range(1, N).ToArray();
127+
_target = N;
128+
}
129+
130+
[Benchmark]
131+
[BenchmarkCategory(Categories.ZLinq)]
132+
public long ZLinq()
133+
{
134+
return _nums.AsValueEnumerable().LongCount(i => i <= _target);
135+
}
136+
137+
[Benchmark]
138+
[BenchmarkCategory(Categories.LINQ)]
139+
public long Linq()
140+
{
141+
return _nums.LongCount(i => i <= _target);
142+
}
143+
}

src/ZLinq/Linq/LongCount.cs

+39
Original file line numberDiff line numberDiff line change
@@ -60,5 +60,44 @@ public static Int64 LongCount<TEnumerator, TSource>(this ValueEnumerable<TEnumer
6060
}
6161
}
6262

63+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
64+
public static Int64 LongCount<TSource>(this ValueEnumerable<FromArray<TSource>, TSource> source, Func<TSource, Boolean> predicate)
65+
{
66+
ArgumentNullException.ThrowIfNull(predicate);
67+
68+
var array = source.Enumerator.GetSource();
69+
if (array.GetType() != typeof(TSource[]))
70+
{
71+
return LongCount(array, predicate);
72+
}
73+
74+
var longCount = 0;
75+
76+
var span = (ReadOnlySpan<TSource>)array;
77+
for (int i = 0; i < span.Length; i++)
78+
{
79+
if (predicate(span[i]))
80+
{
81+
longCount++;
82+
}
83+
}
84+
85+
return longCount;
86+
87+
[MethodImpl(MethodImplOptions.NoInlining)]
88+
static Int64 LongCount(TSource[] array, Func<TSource, Boolean> predicate)
89+
{
90+
var longCount = 0;
91+
for (int i = 0; i < array.Length; i++)
92+
{
93+
if (predicate(array[i]))
94+
{
95+
longCount++;
96+
}
97+
}
98+
return longCount;
99+
}
100+
}
101+
63102
}
64103
}

0 commit comments

Comments
 (0)