Java - for循环终止表达式之间的区别 [英] Java - Difference between for loop terminating expression

查看:122
本文介绍了Java - for循环终止表达式之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是好奇:这两个循环实现之间的速度和性能是否存在差异?假设 size()方法返回处理一组元素的数组,集合或对象的长度(实际上它来自 XOM api)。

I'm just curious: Is there a difference on speed and performance between this two loops implementation? Assume that size() method returns the length of the array,collection, or object that handles a group of elements (actually it's from XOM api).

实施1:

int size = someArray.size();
for (int i = 0; i < size; i++) {
    // do stuff here
}

实施2:

for (int i = 0; i < someArray.size(); i++) {
    // do stuff here
}


推荐答案

从绩效的角度来看,差别不大。这是因为可以优化循环,以便内联size()查找,导致性能差异很小。

From a performance point of view, there is little difference. This is because a loop can be optimized so that the size() lookup is inlined, resulting in very little performance difference.

主要区别在于循环时大小是否发生变化。第一种情况将尝试迭代固定次数。在第二种情况下,迭代次数将取决于最终大小()。

The main difference is if the size changes while looping. The first case will try to iterate a fixed number of times. In the second case, the number of iterations will depend on the final size().

这篇关于Java - for循环终止表达式之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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