Java循环效率(“for”vs.“foreach”) [英] Java loop efficiency ("for" vs. "foreach")

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

问题描述

对于那些熟悉JVM编译和优化技巧的人来说,问题是: - )

是否有任何for和foreach

考虑以下两个例子:

  public void forLoop(String [] text)
{
if(text!= null)
{
for(int i = 0; i< text.length; i ++ )
{
//做一些文本[i]
}
}
}

public void foreachLoop(String [] text )
{
if(text!= null)
{
for(String s:text)
{
//用s与文本[i]
}
}
}



forLoop 快于或慢于 foreachLoop



假设在这两种情况下,文本数组不需要进行完整性检查,是否有明显的赢家或者仍然离得太近编辑:正如在一些答案中指出的,数组的性能应该是相同的,而foreach模式可能会稍微好一些抽象数据类型如列表。另请参阅此答案讨论这个主题。 JLS第14.14.2部分:


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

$ $ $ $ $ $ c $ T $]
L1:L2:... Lm:
for(int i = 0; i< a.length; i ++){
VariableModifiersopt类型标识符= a [i];





$ b换句话说, ,我希望他们最终被编译为相同的代码。

肯定有一个明显的赢家:增强的for循环更易读。这应该是你最关心的问题 - 当你已经证明最可读的表单的表现不如你想要的的时候,你甚至应该考虑微观优化这种事情。


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

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

Consider the following two examples:

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]
        }
    }
}

Is forLoop faster or slower than foreachLoop?

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?

EDIT: 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.

解决方案

From 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
}

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

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”vs.“foreach”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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