我正在编写一个游戏引擎,其中一组对象保存在一个ArrayList
使用 for 循环进行迭代。显然,效率相当重要,所以我想知道循环的效率。
for (String extension : assetLoader.getSupportedExtensions()) {
// do stuff with the extension here
}
Where getSupportedExtension()
返回一个ArrayList
of String
s。我想知道的是,是否每次循环迭代新扩展时都会调用该方法。如果是这样,这样做会更有效吗:
ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();
for (String extension : supportedExtensions) {
// stuff
}
?提前致谢。
根据规范,习语
for (String extension : assetLoader.getSupportedExtensions()) {
...
}
扩展到
for (Iterator<String> it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();)
{
String extension = it.next();
...
}
因此,您询问的调用仅在循环初始化时发生一次。它是其方法被重复调用的迭代器对象。
但是,如果您确实对应用程序的性能感兴趣,那么您应该确保您关注的是大胜利而不是像这样的小人物。让 getter 调用成为任何代码段中的瓶颈几乎是不可能的。对于在 HotSpot 上运行的应用程序来说,这会加倍,它将内联该 getter 调用并将其转变为直接字段访问。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)