循环条件中方法调用的效率 [英] Efficiency of method call in for loop condition

查看:90
本文介绍了循环条件中方法调用的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个游戏引擎,其中使用for循环迭代在 ArrayList 中保存的一组对象。显然,效率是相当重要的,所以我想知道循环的效率。

I am writing a game engine, in which a set of objects held in a ArrayList are iterated over using a for loop. Obviously, efficiency is rather important, and so I was wondering about the efficiency of the loop.

for (String extension : assetLoader.getSupportedExtensions()) {
    // do stuff with the extension here
}

其中 getSupportedExtension()返回 字符串 ArrayList 。我想知道的是,每次循环遍历新扩展时是否调用该方法。如果是这样,做类似的事情会更有效:

Where getSupportedExtension() returns an ArrayList of Strings. What I'm wondering is if the method is called every time the loop iterates over a new extension. If so, would it be more efficient to do something like:

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();
    ...
}

因此,您询问的电话只发生一次,在循环初始化时间。它是迭代器对象,其方法被重复调用。

Therefore the call you ask about occurs only once, at loop init time. It is the iterator object whose methods are being called repeatedly.

但是,如果你真的对应用程序的性能感兴趣,那么你应该确保你的注意力集中关于大赢,而不是像这样的小土豆。几乎不可能将getter call作为任何代码中的瓶颈而脱颖而出。对于在HotSpot上运行的应用程序来说,这是双倍的,它将内联getter调用并将其转换为直接字段访问。

However, if you are honestly interested about the performance of your application, then you should make sure you're focusing on the big wins and not small potatoes like this. It is almost impossible to make a getter call stand out as a bottleneck in any piece of code. This goes double for applications running on HotSpot, which will inline that getter call and turn it into a direct field access.

这篇关于循环条件中方法调用的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆