Skip to content

Commit e9219d7

Browse files
committed
optimize the first operator in a frozen-sequence to improve performance by reducing overhead in item access
1 parent 7988688 commit e9219d7

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

Sources/Falko.Common.Sequences/Sequences/FrozenSequence.Operator.First.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,23 @@ public T First()
1818

1919
public T First(Func<T, bool> predicate)
2020
{
21+
var itemsCount = _itemsCount;
22+
23+
if (itemsCount is 0) SequenceExceptions.ThrowIfEmpty(itemsCount);
24+
2125
ArgumentNullException.ThrowIfNull(predicate);
2226

23-
foreach (ref readonly var item in AsSpan())
27+
scoped ref var itemsReference = ref MemoryMarshal.GetArrayDataReference(_items);
28+
29+
for (var itemIndex = 0; itemIndex < itemsCount; itemIndex++)
2430
{
31+
var item = Unsafe.Add(ref itemsReference, itemIndex);
32+
2533
if (predicate(item)) return item;
2634
}
2735

2836
SequenceExceptions.ThrowNotMatchAny();
29-
return default!; // This line is unreachable
37+
return default; // This line is unreachable
3038
}
3139

3240
[MethodImpl(MethodImplOptions.AggressiveInlining)]

0 commit comments

Comments
 (0)