【发布时间】:2012-03-02 20:17:51
【问题描述】:
(对于那些熟悉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]
}
}
}
forLoop 比 foreachLoop 快还是慢?
假设在这两种情况下 text 数组都不需要任何完整性检查,是否有明显的赢家或仍然太接近而无法进行调用?
编辑:正如一些答案中所述,数组的性能应该相同,而“foreach”模式对于像列表这样的抽象数据类型可能会稍微好一些。另请参阅讨论该主题的this answer。
【问题讨论】:
-
Answer 256859 确实涵盖了我的问题,但不知何故它没有出现在我所做的搜索中。谢谢大家!
标签: java performance for-loop foreach