Iterate with List(mylist.size){ index -> TODO()} or Map in kotlin Kotlin

32 Views Asked by At

I found this code and I would like know which is more efficient to big lists of elements.

return List(myBigList.size){ index ->
   val element = myBigList[index]
   myConversionFunction(element,param2,param3,param4)
}

I though this code could be replaced by

return myBigList.map{
    myConversionFunction(it,param2,param3,param4)
}

Which way is better if I have a lot of elements to iterate, or you suggest other one?

2

There are 2 best solutions below

0
Joffrey On BEST ANSWER

Both options are just as efficient, you should use the clearest one, which is the second option.

5
user23720313 On

If you have a big list you should consider to not use List, because it's load everything in memory. In kotlin consider using Sequences (aka streams in Java) https://kotlinlang.org/docs/sequences.html#from-an-iterable which is lazily by nature and avoid loading every element of your "big list" in memory.