gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:13:43 26 4
gpt4 key购买 nike

(对于那些熟悉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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com