Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/Arch/Core/Query.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Diagnostics.Contracts;
using Arch.Core.Extensions;
using Arch.Core.Extensions.Internal;
using Arch.Core.Utils;
Expand Down Expand Up @@ -571,6 +572,22 @@ internal Query(Archetypes allArchetypes, QueryDescription description)
_queryDescription = description;
}

/// <summary>
/// Counts all <see cref="Entity"/>s that match this query.
/// </summary>
[Pure]
public int CountEntities()
{
var counter = 0;
foreach (var archetype in GetArchetypeIterator())
{
var entities = archetype.EntityCount;
counter += entities;
}

return counter;
}

/// <summary>
/// Checks whether the specified <see cref="BitSet"/> matches.
/// </summary>
Expand Down
21 changes: 17 additions & 4 deletions src/Arch/Core/World.cs
Original file line number Diff line number Diff line change
Expand Up @@ -410,17 +410,30 @@ public void Destroy(Entity entity)
[Pure]
public Query Query(in QueryDescription queryDescription)
{
// Looping over all archetypes, their chunks and their entities.
var queryCache = QueryCache; // Storing locally to only access the QueryCache once
var queryCache = QueryCache; // Store locally to only access the field once

#if NET6_0_OR_GREATER
ref var queryRef = ref CollectionsMarshal.GetValueRefOrAddDefault(queryCache, queryDescription, out bool exists);
if (exists)
{
return queryRef!;
}
else
{
var newQuery = new Query(Archetypes, queryDescription);
queryRef = newQuery;
return newQuery;
}
#else
if (queryCache.TryGetValue(queryDescription, out var query))
{
return query;
}

query = new Query(Archetypes, queryDescription);
queryCache[queryDescription] = query;

queryCache.Add(queryDescription, query);
return query;
#endif
}

/// <summary>
Expand Down
Loading