本文介绍了Java 循环效率(“for"与“foreach")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(A question for those who know well the JVM compilation and optimization tricks... :-)

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

Is there any of the "for" and "foreach" patterns clearly superior to the other?

考虑以下两个例子:

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 数组都不需要任何健全性检查,是否有明显的赢家或仍然太接近而无法拨打电话?

Assuming that in both cases the text array did not need any do sanity checks, is there a clear winner or still too close to make a call?

如某些答案中所述,数组的性能应该相同,而foreach"模式对于抽象数据类型(如列表)可能稍好一些.另请参阅此答案 讨论主题.

As noted in some of the answers, the performance should be identical for arrays, whereas the "foreach" pattern could be slightly better for Abstract Data Types like a List. See also this answer which discusses the subject.

推荐答案

来自 JLS 第 14.14.2 节:

否则,表达式必须有一个数组类型,T[].让 L1 ... Lm 是紧接在增强的 for 语句之前的标签序列(可能是空的).那么增强的for语句的含义由以下基本的for语句给出:

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

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

In other words, I'd expect them to end up being compiled to the same code.

绝对有一个明显的赢家:增强的 for 循环更具可读性.这应该是您的主要关注点 - 只有当您证明最易读的表单没有达到您想要的效果时,您才应该考虑对这类事情进行微优化.

There's definitely a clear winner: the enhanced for loop is more readable. That should be your primary concern - you should only even consider micro-optimizing this sort of thing when you've proved that the most readable form doesn't perform as well as you want.

这篇关于Java 循环效率(“for"与“foreach")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:50
查看更多