ModernUO/Projects/Server/Items/Item.Enumerable.cs
Kamron Batman c552f65673
perf: Eliminates allocations in Container searching. (#2409)
## Summary

Removes per-call heap allocations from `Container`'s consume / find / group hot paths and from `BaseCreature.OnDeath`'s fame/karma tracking. The headline wins: kill the `List<List<Item>>` + `Item[][]` + `int[]` grouping bridges in `ConsumeTotal*` / `ConsumeTotalGrouped*` / `GetBestGroupAmount*`, and kill the per-call `Predicate<Item>` allocations in `FindItemsByType(Type)` / `FindItemsByType(Type[])`.

### `Container.cs`

- `ConsumeTotal`, `ConsumeTotalGrouped`, `GetBestGroupAmount` now share four streaming helpers (`HasAmount`, `TryFindGroupMeetingAmount`, `BestGroupTotal`, `ConsumeSlice`) backed by `PooledRefList` instead of allocating per-group lists and jagged arrays. Two-phase validate-then-consume pattern preserved — all-or-nothing semantics for spell reagents, vendor pay, and crafting still hold.
- `(Type)` / `(Type[])` / `(Type[][])` overload trios collapsed to single `ReadOnlySpan<Type>` + `ReadOnlySpan<int>` implementations. Implicit `T[] → ReadOnlySpan<T>` conversion means UOContent callers compile unchanged.
- Unused overloads deleted: `ConsumeTotalGrouped(Type)`, `ConsumeTotalGrouped(Type[][])`, `GetBestGroupAmount(Type)`, `GetBestGroupAmount(Type[][])`, plus the never-called `TryDropItems` hook and its private `ItemStackEntry` struct.
- Fixes a `PooledRefList` leak in `GetBestGroupAmount(Type[], …)` (missing `using`).
- `m_ContainerData` / `m_Items` / `m_TotalGold` / `m_TotalItems` / `m_TotalWeight` / `ContainerData.m_Table` / `ContainerData.logger` renamed to the underscored convention. `m_Items` cross-file rename for the Container-side references in `Item.cs`; `Item.CompactInfo.m_Items` deliberately left alone (separate effort).
- `CheckHold` parent walk simplified; trivial dispatch methods (`CheckHold` overloads, `OnItemAdded`, `OnItemRemoved`, `OnStackAttempt`) get `[MethodImpl(AggressiveInlining)]`; `Destroy` and `DisplayTo` cache `Items` outside the loop; dead comments removed.

### `Item.Enumerable.cs`

- `FindItemsByType(Type)` previously allocated a `Predicate<Item>` per call (method-group conversion). `FindItemsByType(Type[])` allocated a closure capturing `types`. Both now construct the enumerator with a `Type` / `ReadOnlySpan<Type>` field directly, no delegate.
- `FindItemsByTypeEnumerator<T>` gains two constructors plus a `Matches(T)` helper that picks the right filter inline. Constructor chaining via a private 2-arg seed constructor incidentally fixes a pre-existing bug where `PooledRefQueue` was always rented at capacity 0 because `_recurse` hadn't been assigned yet.
- `(Type[])` overload of `FindItemsByType` becomes `(ReadOnlySpan<Type>)`.
- `EnumerateItemsByType(Type)` / `EnumerateItemsByType(ReadOnlySpan<Type>)` / `ListItemsByType(Type)` / `ListItemsByType(ReadOnlySpan<Type>)` simplified to delegate to the new alloc-free overloads instead of filtering manually.

### `Utility.cs`

- `InTypeList<T>(this T, Type[])` and `InTypeList(this Type, Type[])` switched to `ReadOnlySpan<Type>`.

### `BaseCreature.cs`

- `OnDeath` per-death `List<Mobile>` / `List<int>` / `List<int>` for fame/karma tracking switched to `PooledRefList`.
2026-04-25 13:40:21 -07:00

321 lines
12 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Item.Enumerable.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Server.Collections;
namespace Server;
public partial class Item
{
/// <summary>
/// Performs a breadth-first search through all the <see cref="Item" />s and
/// nested <see cref="Item" />s within this <see cref="Item" />.
/// </summary>
/// <remarks>
/// DO NOT consume, delete, or move items while iterating with any FindItemByType or FindItems overloads
/// </remarks>
/// <example>
/// <code>
/// var total = 0;
///
/// foreach (var gold in cont.FindItemsByType&lt;Gold&gt;())
/// {
/// total += gold.Amount;
/// }
/// </code>
/// </example>
/// <typeparam name="T">Type of objects being searched for</typeparam>
/// <param name="recurse">
/// Optional: If true, the search will recursively
/// check any nested <see cref="Item" />s; otherwise, nested
/// <see cref="Item" />s will not be searched.
/// </param>
/// <param name="predicate">
/// Optional: A predicate to check if the <see cref="Item" />
/// of type <typeparamref name="T" /> is one of the targets of the search.
/// </param>
/// <returns>
/// An enumerator for iterating through <see cref="Item" />s of type <typeparamref name="T" /> that match the optional
/// <paramref name="predicate" />.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FindItemsByTypeEnumerator<T> FindItemsByType<T>(bool recurse = true, Predicate<T> predicate = null)
where T : Item => new(this, recurse, predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FindItemsByTypeEnumerator<Item> FindItemsByType(Type type, bool recurse = true) =>
new(this, recurse, type);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FindItemsByTypeEnumerator<Item> FindItemsByType(ReadOnlySpan<Type> types, bool recurse = true) =>
new(this, recurse, types);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FindItemsByTypeEnumerator<Item> FindItems(bool recurse = true, Predicate<Item> predicate = null) =>
new(this, recurse, predicate);
/// <summary>
/// Safely enumerates items using a breadth-first search through all the <see cref="Item" />s and
/// nested <see cref="Item" />s within this <see cref="Item" />.
/// </summary>
/// <remarks>
/// Use EnumerateItemsByType for situations where the item might be manipulated, consumed, or moved.
/// Note: This method scans through the container before returning the enumerator for iteration and therefore
/// incurs a performance penalty from the overhead.
/// </remarks>
/// <example>
/// <code>
/// using var queue = cont.EnumerateItemsByType&lt;Item&gt;();
/// foreach (var item in queue)
/// {
/// if (item.LootType is not LootType.Blessed)
/// {
/// item.Delete();
/// }
/// }
/// </code>
/// </example>
/// <typeparam name="T">Type of objects being searched for</typeparam>
/// <param name="recurse">
/// Optional: If true, the search will recursively
/// check any nested <see cref="Item" />s; otherwise, nested
/// <see cref="Item" />s will not be searched.
/// </param>
/// <param name="predicate">
/// Optional: A predicate to check if the <see cref="Item" />
/// of type <typeparamref name="T" /> is one of the targets of the search.
/// </param>
/// <returns>
/// An enumerator for iterating through <see cref="Item" />s of type <typeparamref name="T" /> that match the optional
/// <paramref name="predicate" />.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefQueue<T> EnumerateItemsByType<T>(bool recurse = true, Predicate<T> predicate = null) where T : Item
{
var queue = PooledRefQueue<T>.Create(128);
foreach (var item in FindItemsByType(recurse, predicate))
{
queue.Enqueue(item);
}
return queue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefQueue<Item> EnumerateItemsByType(Type type, bool recurse = true)
{
var queue = PooledRefQueue<Item>.Create(128);
foreach (var item in FindItemsByType(type, recurse))
{
queue.Enqueue(item);
}
return queue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefQueue<Item> EnumerateItemsByType(ReadOnlySpan<Type> types, bool recurse = true)
{
var queue = PooledRefQueue<Item>.Create(128);
foreach (var item in FindItemsByType(types, recurse))
{
queue.Enqueue(item);
}
return queue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefQueue<Item> EnumerateItems(bool recurse = true, Predicate<Item> predicate = null) =>
EnumerateItemsByType(recurse, predicate);
public PooledRefList<T> ListItemsByType<T>(bool recurse = true, Predicate<T> predicate = null) where T : Item
{
var list = PooledRefList<T>.Create(128);
foreach (var item in FindItemsByType(recurse, predicate))
{
list.Add(item);
}
return list;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefList<Item> ListItemsByType(Type type, bool recurse = true)
{
var list = PooledRefList<Item>.Create(128);
foreach (var item in FindItemsByType(type, recurse))
{
list.Add(item);
}
return list;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefList<Item> ListItemsByType(ReadOnlySpan<Type> types, bool recurse = true)
{
var list = PooledRefList<Item>.Create(128);
foreach (var item in FindItemsByType(types, recurse))
{
list.Add(item);
}
return list;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PooledRefList<Item> ListItems(bool recurse = true, Predicate<Item> predicate = null) =>
ListItemsByType(recurse, predicate);
public ref struct FindItemsByTypeEnumerator<T> where T : Item
{
private const string InvalidOperation_EnumFailedVersion =
"Item was modified after enumerator was instantiated. Use Item.EnumerateItems method instead for safe enumerations.";
private PooledRefQueue<Item> _containers;
private Span<Item> _items;
private int _index;
private T _current;
private readonly bool _recurse;
private Item _currentContainer;
private int _version;
// Exactly one filter source is used per enumerator instance, depending on
// which constructor was called. The unused fields stay at default and the
// branches below pick the right path. This avoids the per-call delegate
// allocation that the (Type)/(Type[]) factory methods used to incur.
private readonly Predicate<T> _predicate;
private readonly Type _runtimeType;
private readonly ReadOnlySpan<Type> _runtimeTypes;
public FindItemsByTypeEnumerator(Item container, bool recurse, Predicate<T> predicate)
: this(container, recurse) => _predicate = predicate;
public FindItemsByTypeEnumerator(Item container, bool recurse, Type runtimeType)
: this(container, recurse) => _runtimeType = runtimeType;
public FindItemsByTypeEnumerator(Item container, bool recurse, ReadOnlySpan<Type> runtimeTypes)
: this(container, recurse) => _runtimeTypes = runtimeTypes;
private FindItemsByTypeEnumerator(Item container, bool recurse)
{
_recurse = recurse;
_containers = PooledRefQueue<Item>.Create(recurse ? 64 : 0);
if (container != null)
{
var items = container.LookupItems();
if (items != null)
{
_items = CollectionsMarshal.AsSpan(items);
}
_currentContainer = container;
_version = container.LookupContainerVersion();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext() => SetNextItem() || _recurse && SetNextContainer();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool SetNextContainer()
{
while (_containers.TryDequeue(out var c))
{
_currentContainer = c;
_items = CollectionsMarshal.AsSpan(c.LookupItems());
_index = 0;
_version = c.LookupContainerVersion();
if (SetNextItem())
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool Matches(T t)
{
if (_runtimeType is not null)
{
return _runtimeType.IsInstanceOfType(t);
}
if (_runtimeTypes.Length > 0)
{
return t.GetType().InTypeList(_runtimeTypes);
}
return _predicate?.Invoke(t) != false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool SetNextItem()
{
if (_version != _currentContainer.LookupContainerVersion())
{
throw new InvalidOperationException(InvalidOperation_EnumFailedVersion);
}
while (_index < _items.Length)
{
var item = _items[_index++];
if (_recurse && item.LookupItems() is { Count: > 0 })
{
_containers.Enqueue(item);
}
if (item is T t && Matches(t))
{
if (_version != _currentContainer.LookupContainerVersion())
{
throw new InvalidOperationException(InvalidOperation_EnumFailedVersion);
}
_current = t;
return true;
}
}
return false;
}
public T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _current;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose() => _containers.Dispose();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FindItemsByTypeEnumerator<T> GetEnumerator() => this;
}
}