【发布时间】:2017-07-15 10:35:00
【问题描述】:
对于一般的 Android 开发,执行以下操作是否更昂贵: (例一)
for(int x=0; x < largeObjectCollection.size(); x++){
largeObjectCollection.get(x).SomeValueOne = "Sample Value 1";
largeObjectCollection.get(x).SomeValueTwo = "Sample Value 2";
largeObjectCollection.get(x).SomeValueThree = "Sample Value 3" ;
//Continues on to over 30 properties...
}
关于这个实现(示例 2)
for(int x=0; x < largeObjectCollection.size(); x++){
SampleObjectIns myObject = largeObjectCollection.get(x);
myObject.SomeValueOne = "Sample Value 1";
myObject.SomeValueTwo = "Sample Value 2";
myObject.SomeValueThree = "Sample Value 3" ;
//Continues on to over 30 properties...
}
当多次使用 .get() 而不是每次迭代都创建该对象的新实例时,我找不到任何性能影响细分。
我认为.get() 在资源方面的使用并不多,因为元素的位置是已知的,但是在处理许多属性时,最好只获取该对象一次,如示例二所示?
【问题讨论】:
-
对于
ArrayList(或其他RandomAccess类),性能差异将很小。当然,如果你不需要xfor (SampleObjectIns myObject : largeObjectCollection) {,使用增强的for循环会更整洁;但这基本上是第二种方式。 -
@AndyTurner 谢谢,我正在阅读 2015 年 (blog.jooq.org/2015/02/05/…) 的一篇文章,指出迭代器实际上效率不高,第 3 条。这让我想到了我的代码,它主要使用
enhanced-for-loops,因此出现了这个问题。您是否推荐任何涵盖这些主题的书籍? -
这一点的第一行:“现在,这个建议确实不适用于一般用例”。您问题的第一行:“对于一般的 Android 开发”。
-
@AndyTurner 好点
标签: java android performance