2017-09-19 33 views
1

我上有什么优点/每种方法的优缺点困惑(假设我需要同时使用indexproduct):科特林 - “forEachIndexed”之间的差异“为”循环

products.forEachIndexed{ index, product -> 
    ... 
} 

for ((index, product) in products.withIndex()) { 
    ... 
} 

products这里是一个简单的集合。

是否有任何性能/最佳实践/等论点来比较优先选择一个?

回答

1

不,它们是一样的。您可以阅读forEachIndexedwithIndex的来源。

public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T) -> Unit): Unit { 
    var index = 0 
    for (item in this) action(index++, item) 
} 


public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> { 
    return IndexingIterable { iterator() } 
} 

forEachIndexed使用一个局部变量来计算,而对于withIndex迭代器也使用VAR来计算索引创建一个装饰的指标。理论上,withIndex创建一个更多的包装层,但性能应该是相同的。