Skip to content

Commit

Permalink
ECS - optimize EntityStore.GetEntityById()
Browse files Browse the repository at this point in the history
  • Loading branch information
friflo committed Aug 1, 2024
1 parent c47cee6 commit c087a27
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
6 changes: 6 additions & 0 deletions src/ECS/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,12 @@ internal Entity(EntityStore entityStore, int id) {
Id = id;
Revision = store.nodes[id].revision;
}

internal Entity(EntityStore entityStore, int id, short revision) {
store = entityStore;
Id = id;
Revision = revision;
}

/// <summary>
/// Returns an <see cref="EntityBatch"/> to add/remove components or tags to/from this entity using the batch.<br/>
Expand Down
5 changes: 3 additions & 2 deletions src/ECS/EntityStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,9 @@ public ref readonly EntityNode GetEntityNode(int id) {
/// </summary>
/// <exception cref="IndexOutOfRangeException"> In case passed <paramref name="id"/> invalid (id >= <see cref="Capacity"/>). </exception>
public Entity GetEntityById(int id) {
if (0 <= id && id < nodes.Length) {
return new Entity(this, id);
var localNodes = nodes;
if (0 <= id && id < localNodes.Length) {
return new Entity(this, id, localNodes[id].revision);
}
throw IdOutOfRangeException(this, id);
}
Expand Down
16 changes: 15 additions & 1 deletion src/Tests/ECS/Entity/Test_Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,20 @@ public static void Assert_GetEntityById()
AreEqual("id: 4. expect in [0, current max id: 3]", e!.Message);
}

[Test]
public static void Assert_GetEntityById_Perf() {
var count = 10; // 10_000_000_000L;
// Assert_GetEntityById_Perf() - count: 10000000000, duration: 3238
var store = new EntityStore();
store.CreateEntity(2);
var sw = new Stopwatch();
sw.Start();
for (long n = 0; n < count; n++) {
store.GetEntityById(2);
}
Console.WriteLine($"Assert_GetEntityById_Perf() - count: {count}, duration: {sw.ElapsedMilliseconds}");
}

[Test]
public static void Assert_TryGetEntityById()
{
Expand All @@ -187,7 +201,7 @@ public static void Assert_TryGetEntityById()
IsFalse(store.TryGetEntityById(4, out entity));
IsTrue (entity.IsNull);
}

[Test]
public static void Test_EntityStore_CloneEntity()
{
Expand Down

0 comments on commit c087a27

Please sign in to comment.