我找到了这段代码,我想知道哪个对于大元素列表更有效。
return List(myBigList.size){ index ->
val element = myBigList[index]
myConversionFunction(element,param2,param3,param4)
}
我虽然这个代码可以被替换为
return myBigList.map{
myConversionFunction(it,param2,param3,param4)
}
如果我有很多元素需要迭代,哪种方法更好,或者您建议其他方法?
如果你有一个很大的列表,你应该考虑不要使用List,因为它会将所有内容加载到内存中。在 kotlin 中,考虑使用序列(Java 中的流)https://kotlinlang.org/docs/sequences.html#from-an-iterable,它本质上是懒惰的,避免在内存中加载“大列表”的每个元素.