增强了循环性能 [英] Enhanced for loop performance

查看:58
本文介绍了增强了循环性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此我和我的朋友吵了一架. 考虑以下代码段,

I had an argument with my friend regarding this. Consider the below snippet,

for(i=0; i<someList.size(); i++) {
    //some logic
    }

此处someList.size()将在每次迭代时执行,因此建议将该大小计算迁移到循环外部(循环之前).

Here someList.size() will be executed for every iteration, so it is recommended to migrate this size calculation to outside(before) the loop.

现在当我使用扩展的for循环时会发生什么情况,

Now what happens when I use an extended for loop like this,

for(SpecialBean bean: someBean.getSpecialList()) {
//some logic
}

是否有必要将someBean.getSpecialList()移到循环之外? 如果我原样保留第二个片段,someBean.getSpecialList()将执行多少次?

Is it necessary to move someBean.getSpecialList() to outside the loop? How many times will someBean.getSpecialList() execute if I were to retain the 2nd snippet as it is?

推荐答案

重复调用list.size()不会导致任何性能损失. JIT编译器很可能会内联它,即使不这样做,它仍然会非常便宜,因为它只涉及读取字段的值.

Repeated calls to list.size() won't result in any performance penalty. The JIT compiler will most probably inline it and even if it doesn't, it will still be quite inexpensive because it just involves reading the value of a field.

第一个示例的一个更为严重的问题是,循环主体必须包含list.get(i),对于LinkedList,使 i 元素具有O( i ),由于指针的追逐,其成本具有相当可观的恒定系数,这转化为CPU级别上与数据相关的负载. CPU的预取器无法优化此访问模式.

A much more serious problem with your first example is that the loop body will have to involve list.get(i) and for a LinkedList, acessing the i th element has O(i) cost with a quite significant constant factor due to pointer chasing, which translates to data-dependent loads on the CPU level. The CPU's prefetcher can't optimize this access pattern.

这意味着当应用于LinkedList时,总体计算复杂度将为O(n 2 ).

This means that the overall computational complexity will be O(n2) when applied to a LinkedList.

您的第二个示例通过Iterator编译为迭代,并且只会对someBean.getSpecialList().iterator()进行一次评估. iterator.next()的成本在所有情况下都是恒定的.

Your second example compiles to iteration via Iterator and will evaluate someBean.getSpecialList().iterator() only once. The cost of iterator.next() is constant in all cases.

这篇关于增强了循环性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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