Java 循环效率 ("for"与 "foreach")

标签 java performance for-loop foreach

(对于那些熟悉JVM编译和优化技巧的人的问题......:-)

是否有任何“for”和“foreach”模式明显优于另一个?

考虑以下两个例子:

public void forLoop(String[] text)
{
    if (text != null)
    {
        for (int i=0; i<text.length; i++)
        {
            // Do something with text[i]
        }
    }
}

public void foreachLoop(String[] text)
{
    if (text != null)
    {
        for (String s : text)
        {
            // Do something with s, exactly as with text[i]
        }
    }
}

forLoopforeachLoop 快还是慢?

假设在这两种情况下 text 数组都不需要任何完整性检查,是否有明显的赢家或仍然太接近而无法调用?

编辑:正如一些答案中所述,数组的性能应该相同,而“foreach”模式对于像列表这样的抽象数据类型可能会稍微好一些。另见 this answer其中讨论了这个主题。

最佳答案

来自 section 14.14.2 of the JLS :

Otherwise, the Expression necessarily has an array type, T[]. Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement. Then the meaning of the enhanced for statement is given by the following basic for statement:

T[] a = Expression;
L1: L2: ... Lm:
for (int i = 0; i < a.length; i++) {
        VariableModifiersopt Type Identifier = a[i];
        Statement
}

换句话说,我希望它们最终被编译成相同的代码。

绝对有一个明显的赢家:增强的 for 循环更具可读性。这应该是您最关心的问题 - 您甚至应该考虑在您已经证明最易读的表单的性能不如您想要的那样好时,才考虑对这类事情进行微优化。

关于Java 循环效率 ("for"与 "foreach"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9226483/

相关文章:

javascript - 将属性添加到 for 循环中的最后一项

linux - 多次复制的文件内容

java - java中创建单词的高效算法

python - 高效递归迭代器: Possible?

silverlight - 性能分析 Windows Phone 7 应用程序 (SL/XNA)

python - 与 C 等效程序相比,解压例程非常慢?

Python Pandas groupby forloop & Idxmax

java - 使用 Netty 解码 GET 和 POST 方法

java - 无法运行jsp文件,jSTL

java - 将 boolean 值转换为 Int