【问题标题】:Kotlin - Difference between "forEachIndexed" and "for in" loopKotlin - “forEachIndexed”和“for in”循环之间的区别
【发布时间】:2017-09-19 23:51:04
【问题描述】:

我对这些方法的优缺点感到困惑(假设我需要同时使用indexproduct):

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

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

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

是否有任何性能/最佳实践/等论据来选择一个胜过另一个?

【问题讨论】:

    标签: for-loop foreach kotlin


    【解决方案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 使用本地 var 来计算索引,而 withIndex 为迭代器创建装饰器,它也使用 var 来计算索引。理论上,withIndex 再创建一层包装,但性能应该相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-05
      • 2015-02-25
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 2015-11-18
      相关资源
      最近更新 更多