我正在用 Java 构建一个新的实体系统。我想知道我提出的方法是否会导致任何问题,无论是架构方面还是性能方面。
我想:
...
for (Entity entity : entities)
{
for (Entry<String, Component> entry : entity.components.entrySet()) //collection is a Map
{
Component component = entry.getValue();
component.update(deltaTime);
}
}
...
与不受欢迎的替代方案相比:
...
for (Entity entity : entities)
{
if (entity.componentA != null)
entity.componentA.update(deltaTime);
if (entity.componentB != null)
entity.componentB.update(deltaTime);
//etc. for as many components as the entity has. Finite, but possibly many.
}
...
对于第一种方法,我想到了一些关于 HashMap 方法的事情:
- 我会避免不必要的条件(当成千上万的实体被
update()
调用时,这很重要); - 读取访问时间平均为 O(1)(您唯一可能无法获得的时间是在哈希冲突中);
HashMap.entrySet()
必须调用以使用 for-each 语法遍历集合。正如我从文档中了解到的那样,“集合 [set] 由地图支持”。但是,这并不能告诉我 HashMap 是否在内部创建集合,每次都entrySet()
被调用。