Skip to content

Commit f52cca2

Browse files
Improve PartialSort performance (#67)
1 parent b8564b5 commit f52cca2

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

Source/SuperLinq.Async/PartialSort.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,11 @@ static async IAsyncEnumerable<T> _(IAsyncEnumerable<T> source, int count, ICompa
122122
var top = new SortedSet<(T item, int index)>(
123123
ValueTupleComparer.Create<T, int>(comparer, default));
124124

125-
await foreach (var (index, item) in source.Index().WithCancellation(cancellationToken).ConfigureAwait(false))
125+
var index = -1;
126+
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
126127
{
128+
index++;
129+
127130
if (top.Count < count)
128131
{
129132
top.Add((item, index));
@@ -283,9 +286,10 @@ static async IAsyncEnumerable<TSource> _(IAsyncEnumerable<TSource> source, int c
283286
ValueTupleComparer.Create<TKey, int>(comparer, default));
284287
var dic = new Dictionary<(TKey Key, int Index), TSource>(count);
285288

286-
await foreach (var (index, item) in source.Index().WithCancellation(cancellationToken).ConfigureAwait(false))
289+
var index = 0;
290+
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
287291
{
288-
var key = (key: keySelector(item), index);
292+
var key = (key: keySelector(item), index++);
289293
if (top.Count < count)
290294
{
291295
top.Add(key);

Source/SuperLinq/PartialSort.cs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,18 +119,21 @@ public static IEnumerable<T> PartialSort<T>(
119119

120120
static IEnumerable<T> _(IEnumerable<T> source, int count, IComparer<T> comparer)
121121
{
122-
var top = new SortedSet<(T item, int index)>(
122+
var top = new SortedSet<(T Item, int Index)>(
123123
ValueTupleComparer.Create<T, int>(comparer, default));
124124

125-
foreach (var (index, item) in source.Index())
125+
var index = -1;
126+
foreach (var item in source)
126127
{
128+
index++;
129+
127130
if (top.Count < count)
128131
{
129132
top.Add((item, index));
130133
continue;
131134
}
132135

133-
if (comparer.Compare(item, top.Max.item) >= 0)
136+
if (comparer.Compare(item, top.Max.Item) >= 0)
134137
continue;
135138

136139
top.Remove(top.Max);
@@ -283,9 +286,10 @@ static IEnumerable<TSource> _(IEnumerable<TSource> source, int count, Func<TSour
283286
ValueTupleComparer.Create<TKey, int>(comparer, default));
284287
var dic = new Dictionary<(TKey Key, int Index), TSource>(count);
285288

286-
foreach (var (index, item) in source.Index())
289+
var index = 0;
290+
foreach (var item in source)
287291
{
288-
var key = (key: keySelector(item), index);
292+
var key = (key: keySelector(item), index++);
289293
if (top.Count < count)
290294
{
291295
top.Add(key);

0 commit comments

Comments
 (0)