From bd3d8d3dc499166a30da4265f6bd65abf84cd761 Mon Sep 17 00:00:00 2001 From: Martin Evans Date: Mon, 7 Aug 2023 02:23:46 +0100 Subject: [PATCH] Cleaned up multiple enumeration in FixedSizeQueue --- LLama/Common/FixedSizeQueue.cs | 36 +++++++++++++--------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/LLama/Common/FixedSizeQueue.cs b/LLama/Common/FixedSizeQueue.cs index 7e685777..28ae53fc 100644 --- a/LLama/Common/FixedSizeQueue.cs +++ b/LLama/Common/FixedSizeQueue.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Text; namespace LLama.Common { @@ -10,13 +9,15 @@ namespace LLama.Common /// A queue with fixed storage size. /// Currently it's only a naive implementation and needs to be further optimized in the future. /// - public class FixedSizeQueue: IEnumerable + public class FixedSizeQueue + : IEnumerable { - int _maxSize; - List _storage; + private readonly int _maxSize; + private readonly List _storage; public int Count => _storage.Count; public int Capacity => _maxSize; + public FixedSizeQueue(int size) { _maxSize = size; @@ -30,26 +31,20 @@ namespace LLama.Common /// public FixedSizeQueue(int size, IEnumerable data) { -#if NETSTANDARD2_0 - var dataCount = data.Count(); - if (data.Count() > size) +#if !NETSTANDARD2_0 + // Try to check the size without enumerating the entire IEnumerable. This may not be able to get the count, + // in which case we'll have to check later + if (data.TryGetNonEnumeratedCount(out var dataCount) && dataCount > size) throw new ArgumentException($"The max size set for the quene is {size}, but got {dataCount} initial values."); -#else - if (data.TryGetNonEnumeratedCount(out var count) && count > size) - throw new ArgumentException($"The max size set for the quene is {size}, but got {count} initial values."); #endif // Size of "data" is unknown, copy it all into a list _maxSize = size; _storage = new List(data); - // Now check if that list is a valid size + // Now check if that list is a valid size. if (_storage.Count > _maxSize) -#if NETSTANDARD2_0 - throw new ArgumentException($"The max size set for the quene is {size}, but got {dataCount} initial values."); -#else - throw new ArgumentException($"The max size set for the quene is {size}, but got {count} initial values."); -#endif + throw new ArgumentException($"The max size set for the quene is {size}, but got {_storage.Count} initial values."); } /// /// Replace every item in the queue with the given value @@ -58,7 +53,7 @@ namespace LLama.Common /// returns this public FixedSizeQueue FillWith(T value) { - for(int i = 0; i < Count; i++) + for(var i = 0; i < Count; i++) { _storage[i] = value; } @@ -78,16 +73,13 @@ namespace LLama.Common } } - public T[] ToArray() - { - return _storage.ToArray(); - } - + /// public IEnumerator GetEnumerator() { return _storage.GetEnumerator(); } + /// IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator();