我正在用Java构建一个新的实体系统。我想知道我提出的方法是否会导致任何问题,无论是体系结构还是性能方面。
我想:
...
for (Entity entity : entities)
{
for (Entry<String, Component> entry : entity.components.entrySet()) //collection is a Map
{
Component component = entry.getValue();
component.update(deltaTime);
}
}
...
VS。不受欢迎的选择:
...
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()
时非常重要); HashMap.entrySet()
来迭代集合。正如我从文档中理解的那样,“集合[集合]由地图支持”。但是,每次调用entrySet()
时,这都不会告诉我HashMap是否在内部创建集合。答案 0 :(得分:2)
读取访问时间平均为O(1)(唯一一次您可能无法获得哈希冲突);
在for entry中的每个循环中,您无需调用map.get()
。
但是,每次调用entrySet()时,这都不会告诉我HashMap是否在内部创建集合。
不,每次都不会创建新的设置。
您应该编写最干净,最容易阅读和维护的代码。如果性能不够好(即您已对应用程序进行了分析并确定性能问题是由该部分代码引起的),请开始优化。
==&GT;每个循环使用一个。
答案 1 :(得分:1)
第一个版本几乎可以肯定是最好的设计:
如果您真的关心性能并且已经分析这是一个重要的特殊情况,您可能需要考虑为entity.components编写自定义数据结构(例如ComponentList
) ,这将有一个额外的方法updateAll(deltaTime)
来有效地执行所有包含的组件的更新操作。这有几个好处: